我的网站有很多请求,我的数据库连接类有问题 在请求程序连接到数据库时另一个请求来和系统错误。 我的班级在这里
cmd=new SqlCommand();
con=new SqlConnection();
SqlCommand cmdLog = new SqlCommand();
string cns = "";
if(MABP.GetdomainUrl()=="localhost")
{
cns=ConfigurationManager.ConnectionStrings["ConnectionStringClient"].ToString();
} else
{
cns=ConfigurationManager.ConnectionStrings["ConnectionStringServer"].ToString();
}
con.ConnectionString=cns;
cmd.Connection=con;
cmdLog.Connection=con;
try
{
cmd.CommandText = Query;
DataTable dt = new DataTable();
SqlDataAdapter da = new SqlDataAdapter();
da.SelectCommand=cmd;
while(con.State==ConnectionState.Connecting)
{
}
if(ConnectionState.Open!=con.State)
{
con.Open();
}
da.Fill(dt);
while(con.State==ConnectionState.Connecting)
{
}
if(ConnectionState.Closed!=con.State)
{
con.Close();
}
con.Dispose();
cmd.Dispose();
return dt;
} catch(Exception e)
{
return null;
}
我希望你能帮助我
答案 0 :(得分:1)
试试这个:
string sql = "select ....";
string whereToConnect = MABP.GetdomainUrl()=="localhost" ? "ConnectionStringClient" : "ConnectionStringServer";
string connectionString = ConfigurationManager.ConnectionStrings[whereToConnect].ToString();
var dt = new DataTable();
using (var connection = new SqlConnection(connectionString))
{
using (var adapter = new SqlDataAdapter(sql, connection))
{
try
{
adapter.Fill(dt);
}
catch
{
// Deal with exceprion if you want
}
}
}
return dt;