如何在这种情况下访问asp.net中的数据库?

Hello Guys下面是我访问数据库的代码。 当我尝试从多个选项卡打开网站或我在调试模式下打开它时出错!

using System; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; namespace DomeNameSpace { public class DAL { public static string _ConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["xClassConnectionString"].ConnectionString; public static SqlConnection _Connection = null; public static SqlConnection Connection { get { //_Connection.Close(); //private static SqlConnection _Connection = null; if (_Connection == null) { _Connection = new SqlConnection(_ConnectionString); _Connection.Open(); return _Connection; } else if (_Connection.State != System.Data.ConnectionState.Open) { _Connection.Open(); return _Connection; } else { return _Connection; } } } public static DataSet GetDataSet(string sql) { try { SqlCommand cmd = new SqlCommand(sql, Connection); SqlDataAdapter adp = new SqlDataAdapter(cmd); // Connection.Close(); DataSet ds = new DataSet(); adp.Fill(ds); return ds; } catch (SqlException err) { // Replace the error with something less specific. // You could also log the error now. throw new ApplicationException("Data error. " + err.Message.ToString()); } finally { Connection.Close(); } } public static DataTable GetDataTable(string sql) { DataSet ds = GetDataSet(sql); if (ds.Tables.Count > 0) return ds.Tables[0]; return null; } public static int ExecuteSQL(string sql) { try { string BegSql = "BEGIN TRY BEGIN TRANSACTION "; string EndSql = " COMMIT TRANSACTION END TRY BEGIN CATCH ROLLBACK TRANSACTION END CATCH"; string NewSql = BegSql + sql + EndSql; sql = NewSql; SqlCommand cmd = new SqlCommand(sql, Connection); return cmd.ExecuteNonQuery(); } catch (System.Exception ex) { return -1; } finally { Connection.Close(); } } } } 

但我在这里得到了错误 在此处输入图像描述

和输出说

在此处输入图像描述

什么似乎是问题?

单个静态数据库连接是一个着名的坏主意。 它本质上使您的应用程序成为单线程,而Web应用程序本身并不是这样。

不要像这样集中你的连接对象。 创建连接对象不是资源密集型操作。 打开连接本身并不是特别耗费资源,连接池可以为您完成大部分繁重的工作,并且非常优化。

在需要时创建数据库连接对象,尽可能靠近您使用它们的位置,并在完成后立即处理它们。 一般来说,类似于这样的模式:

 public void SomeMethodWhichConnectsToDB() { using (var connection = new SqlConnection()) using (var command = new SqlCommand()) { // do something with the connection, execute the command, etc } } 

您可以将连接的创建封装到(非静态)方法中,以避免代码重复等等。 但是不要反复在内存中重复使用相同的连接对象。 创建它,使用它,在尽可能短的时间内销毁它。

错误是不言自明的,但是你遇到这种问题的原因是因为连接对象是静态的,这意味着你正在为你对数据库进行的所有调用共享这个实例 – 所有执行任何类型的线程数据访问将使用相同的连接,这显然是你不想要的。

您应该做的是在每个方法中创建SQL连接的实例,或者创建一个Utility类,为每个调用返回一个新实例。

例如:

 public class DBUtility { public static DbConnection GetOpenConnection() { var conn = new DBConnection(connectionString); //or whatever type conn.Open(); return conn; } } 

现在在你的方法中:

  public static int ExecuteSQL(string sql) { using (var conn = DBUtility.GetOpenConnection()) { .... } }