【发布时间】:2016-12-28 11:52:37
【问题描述】:
class CommonConnection
{
public class dStructure
{
public static string ConnectionString = "";
}
public SqlConnection Conn;
#region "Connection Procedures"
public string ConnectionString
{
get
{
string sConn = string.Empty;
sConn = @"Server=ServerName;Initial Catalog=Database;User ID=userid;Password=password;";
dStructure.ConnectionString = sConn;
return dStructure.ConnectionString;
}
}
public void cnOpen()
{
try
{
if (Conn == null)
{
Conn = new System.Data.SqlClient.SqlConnection();
}
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
Conn.ConnectionString = ConnectionString;
Conn.Open();
}
catch (SqlException e)
{
SqlConnection.ClearAllPools();
throw e;
}
catch (Exception ex)
{
throw ex;
}
}
public void cnClose()
{
try
{
if ((Conn != null))
{
if (Conn.State == ConnectionState.Open)
{
Conn.Close();
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
Conn = null;
}
}
#endregion
public int ExecuteQuery(string strQuery, Int16 TimeOut = 30)
{
int RecordsAffected;
SqlCommand cmd;
try
{
cnOpen();
cmd = new SqlCommand(strQuery, Conn);
cmd.CommandTimeout = TimeOut;
RecordsAffected = cmd.ExecuteNonQuery();
return RecordsAffected;
}
catch (Exception ex)
{
throw ex;
}
finally
{
cnClose();
cmd = null;
}
}
}
// 尝试了另一个选项,如下所示,
public int ExecuteQuery(string strQuery, short TimeOut = 10)
{
SqlConnection NewConn = new SqlConnection();
try
{
if (NewConn == null)
{
NewConn = new System.Data.SqlClient.SqlConnection();
}
if (NewConn.State == ConnectionState.Open)
{
NewConn.Close();
}
NewConn.ConnectionString = "Server=ServerName;Initial Catalog=Database;User ID=userid;Password=password;";
NewConn.Open();
return new SqlCommand(strQuery, NewConn)
{
CommandTimeout = ((int)TimeOut)
}.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
finally
{
NewConn.Close();
}
}
但仍然遇到同样的问题。 它的桌面应用程序,多线程。但是,虽然对此有更多的查询负载,但我却不允许更改“ConnectionString”属性。连接的当前状态是打开的。 请注意,不是每次我都遇到这个问题,只有在执行更多查询时。
// 更新 2 根据另一个问题中的建议,我尝试使用以下代码,但问题仍然存在。
public int ExecuteQuery(string strQuery, short TimeOut = 10)
{
int executeReader = 0;
try
{
using (SqlConnection connection = new SqlConnection(@"Server=Server;Initial Catalog=DB;User ID=id;Password=Password;"))
{
try
{
connection.Open();
SqlCommand command = new SqlCommand(strQuery, connection);
command.CommandType = CommandType.Text;
command.CommandTimeout = TimeOut;
executeReader = command.ExecuteNonQuery();
}
catch (Exception ex)
{
throw ex;
}
}
return executeReader;
}
catch (Exception ex)
{
throw ex;
}
}
正如那里所建议的,使用命令使用默认 IDisposable,因此无需关闭连接。
【问题讨论】:
-
你试过简单的
new SqlConnection("... connection string ...");吗? -
另外,指出您得到异常的确切位置,因为允许更改 SqlConnection 对象的连接字符串属性。
-
而且代码是不必要的复杂。您首先构造一个新的 SqlConnection 对象,然后输入一个 try/catch,在其中检查变量是否为空,即您刚刚将对象引用放入的那个,所以它不可能。然后检查连接是否打开,但由于它刚刚构建,它将被关闭。然后设置连接字符串并打开它。能否请您简化代码并指出您获得异常的确切位置?
-
@LasseV.Karlsen 他的代码对于一个或两个查询运行良好我也检查过。如果他尝试执行多个查询,则会引发异常。我试图给出答案,但他说这也给出了例外。请也检查我的答案,让我们知道我的答案中有什么不适合他的问题。
-
不起作用的是他在多线程应用程序中执行此操作。他不应该跨多个线程使用同一个连接对象。
标签: c# sql sql-server sqlconnection sqlcommand