【问题标题】:How to access DB in asp.net on this scenario?如何在这种情况下访问 asp.net 中的数据库?
【发布时间】:2014-04-10 21:13:56
【问题描述】:

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

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();
            }
        }

    }
}

但我在这里得到以下错误

输出显示

似乎是什么问题?

【问题讨论】:

  • 为什么你真的需要保持连接静态?您可以在需要时返回连接!如果您仍然需要保持静态,我认为您不需要返回连接,因为它可以访问

标签: c# asp.net database


【解决方案1】:

单一的静态数据库连接是一个众所周知的坏主意。它本质上使您的应用程序成为单线程的,而 Web 应用程序本质上不是。

不要像这样集中你的连接对象。创建连接对象不是资源密集型操作。而且打开连接本身并不是特别占用资源,连接池为您处理了大部分繁重的工作,并且得到了很好的优化。

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

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

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

【讨论】:

    【解决方案2】:

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

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

    例如:

    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()) 
          {
               ....
          }
     }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-01-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-09
      相关资源
      最近更新 更多