C# 程序连接到sql server在我的网站与大量的要求
我的网站有很多要求,我的数据库连接类有问题 在请求程序连接到数据库时,另一个请求出现并导致系统错误。 我的班级在这里C# 程序连接到sql server在我的网站与大量的要求,c#,asp.net,sql-server,C#,Asp.net,Sql Server,我的网站有很多要求,我的数据库连接类有问题 在请求程序连接到数据库时,另一个请求出现并导致系统错误。 我的班级在这里 cmd=new SqlCommand(); con=new SqlConnection(); SqlCommand cmdLog = new SqlCommand(); string cns = ""; if(MABP.GetdomainUrl()=="localhost") { cns=ConfigurationM
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;
}
我希望你能帮我试试这个:
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;
你能显示你收到的错误信息吗?例如,连接没有关闭。连接的当前状态为“正在连接”。执行GetConfigurationItem 3
SqlDataAdapter.Fill
如果连接已关闭,则打开连接执行并关闭连接。如果它是打开的,请执行并保持打开状态。出于安全原因,我读到一些地方,我们应该关闭连接,这是真的吗?@mpourbafrani最好关闭连接,因为它不消耗资源。使用使用
连接将在超出范围时关闭和释放。阅读关于这里的信息。特别是评论部分。谢谢你,我的朋友我做了这件事,但我也有问题