【发布时间】: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();
}
}
}
}
但我在这里得到以下错误
输出显示
似乎是什么问题?
【问题讨论】:
-
为什么你真的需要保持连接静态?您可以在需要时返回连接!如果您仍然需要保持静态,我认为您不需要返回连接,因为它可以访问