SqlCommand 之间的连接未关闭
Connection not close between SqlCommand
我以编程方式创建一个数据库,然后在数据库中创建一个 table。数据库已创建,但未创建 table。
// Create Database
try
{
using (SqlCommand cmd = new SqlCommand(connstr, sqlConn))
{
try
{
sqlConn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
finally
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
// Create table
try
{
using (SqlCommand cmd = new SqlCommand(
"CREATE TABLE dbo.MyTable ("
+ "ID int IDENTITY(1,1) PRIMARY KEY,"
+ "MyProduct nvarchar(100) NOT NULL,"
+ "MyDateTime datetime NOT NULL);"
+ "", sqlConn))
{
sqlConn.Open();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
但是我收到错误消息说我的连接没有关闭。
我尝试反复添加 sqlConn.Close() 到每个 {block} 的末尾,但我仍然遇到同样的错误。创建数据库后如何正确关闭连接然后再次重新打开连接以创建 table?
[编辑]
根据输入的答案,我重构了我的代码,我确信包装 属性 而不会复制 Open()。
// Create Database
try
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionStr))
{
using (SqlCommand cmd = new SqlCommand(connstr, sqlConn))
{
try
{
sqlConn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
finally
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
}
}
}
catch(Exception ex)
{
MessageBox.Show("(1)\n" + ex.ToString());
}
// Create Table
try
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionStr))
{
using (SqlCommand cmd = new SqlCommand("CREATE TABLE dbo.MyTable ("
+ "ID int IDENTITY(1,1) PRIMARY KEY,"
+ "MyProduct nvarchar(100) NOT NULL,"
+ "MyDateTime datetime NOT NULL);"
+ "", sqlConn))
{
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("(2)\n" + ex.ToString());
}
然后我收到错误消息数据库 中已经有一个名为'MyTable' 的对象。但是当我查看 SSMS 时, table 不存在。我现在很迷茫。
我没有看到您关闭了第二次查询的连接。您可以使用 SqlConnection.
的 using 语句包装
仅供参考:如果使用using语句,则不需要显式关闭连接。
string cmdText = "SELECT * FROM SomeTable";
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(...);
}
当您创建 table 时,您尝试打开连接两次。 cmd.Connection
属性 指向与 sqlConn
相同的连接。删除其中一个。
using (SqlCommand cmd = new SqlCommand(
"CREATE TABLE dbo.MyTable ("
+ "ID int IDENTITY(1,1) PRIMARY KEY,"
+ "MyProduct nvarchar(100) NOT NULL,"
+ "MyDateTime datetime NOT NULL);"
+ "", sqlConn))
{
sqlConn.Open();
cmd.Connection.Open(); // don't need this...
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
根据 docs,这是预期的行为。
InvalidOperationException
Cannot open a connection without specifying a data source or server.
or
The connection is already open.
试试这个 Code.May 很有帮助。
public void NewClass()
{
try
{
string query = "if exists(SELECT db_id('{0}'),'TEST') ";
query += "begin ";
query += "print 'All Ready Exists' ";
query += "end ";
query += "else ";
query += "begin ";
query += "create database TEST ";
query += "end ";
lblno.Text = query+"<br>";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
int ans = cmd.ExecuteNonQuery();
cmd.Cancel(); cmd.Dispose();
con.Close(); con.Dispose();
string table = "if exists (select OBJECT_ID('test')) begin ";
table += "print 'all ready' end ";
table += "else begin ";
table += "CREATE TABLE dbo.MyTable (ID int IDENTITY(1,1) PRIMARY KEY,MyProduct nvarchar(100) NOT NULL,MyDateTime datetime NOT NULL) ";
table += "end ";
con = new SqlConnection("Data Source=DESKTOP-0R1BJNQ\HARDIKPATEL;Initial Catalog=" + dbnm + ";Integrated Security=True");
con.Open();
cmd = new SqlCommand(table, con);
cmd.ExecuteNonQuery();
cmd.Cancel(); cmd.Dispose();
con.Close(); con.Dispose();
}
catch(Exception err)
{
lblmsg.Text = err.ToString();
}
}
我以编程方式创建一个数据库,然后在数据库中创建一个 table。数据库已创建,但未创建 table。
// Create Database
try
{
using (SqlCommand cmd = new SqlCommand(connstr, sqlConn))
{
try
{
sqlConn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
finally
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
// Create table
try
{
using (SqlCommand cmd = new SqlCommand(
"CREATE TABLE dbo.MyTable ("
+ "ID int IDENTITY(1,1) PRIMARY KEY,"
+ "MyProduct nvarchar(100) NOT NULL,"
+ "MyDateTime datetime NOT NULL);"
+ "", sqlConn))
{
sqlConn.Open();
cmd.Connection.Open();
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
但是我收到错误消息说我的连接没有关闭。
我尝试反复添加 sqlConn.Close() 到每个 {block} 的末尾,但我仍然遇到同样的错误。创建数据库后如何正确关闭连接然后再次重新打开连接以创建 table?
[编辑]
根据输入的答案,我重构了我的代码,我确信包装 属性 而不会复制 Open()。
// Create Database
try
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionStr))
{
using (SqlCommand cmd = new SqlCommand(connstr, sqlConn))
{
try
{
sqlConn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("DataBase is Created Successfully", "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString(), "MyProgram", MessageBoxButton.OK, MessageBoxImage.Information);
}
finally
{
if (sqlConn.State == ConnectionState.Open)
{
sqlConn.Close();
}
}
}
}
}
catch(Exception ex)
{
MessageBox.Show("(1)\n" + ex.ToString());
}
// Create Table
try
{
using (SqlConnection sqlConn = new SqlConnection(sqlConnectionStr))
{
using (SqlCommand cmd = new SqlCommand("CREATE TABLE dbo.MyTable ("
+ "ID int IDENTITY(1,1) PRIMARY KEY,"
+ "MyProduct nvarchar(100) NOT NULL,"
+ "MyDateTime datetime NOT NULL);"
+ "", sqlConn))
{
sqlConn.Open();
cmd.ExecuteNonQuery();
sqlConn.Close();
}
}
}
catch (Exception ex)
{
MessageBox.Show("(2)\n" + ex.ToString());
}
然后我收到错误消息数据库 中已经有一个名为'MyTable' 的对象。但是当我查看 SSMS 时, table 不存在。我现在很迷茫。
我没有看到您关闭了第二次查询的连接。您可以使用 SqlConnection.
的 using 语句包装仅供参考:如果使用using语句,则不需要显式关闭连接。
string cmdText = "SELECT * FROM SomeTable";
using (var conn = new SqlConnection(connectionString))
using (var cmd = new SqlCommand(cmdText, conn))
{
conn.Open();
cmd.ExecuteNonQuery();
MessageBox.Show(...);
}
当您创建 table 时,您尝试打开连接两次。 cmd.Connection
属性 指向与 sqlConn
相同的连接。删除其中一个。
using (SqlCommand cmd = new SqlCommand(
"CREATE TABLE dbo.MyTable ("
+ "ID int IDENTITY(1,1) PRIMARY KEY,"
+ "MyProduct nvarchar(100) NOT NULL,"
+ "MyDateTime datetime NOT NULL);"
+ "", sqlConn))
{
sqlConn.Open();
cmd.Connection.Open(); // don't need this...
cmd.ExecuteNonQuery();
cmd.Connection.Close();
}
根据 docs,这是预期的行为。
InvalidOperationException
Cannot open a connection without specifying a data source or server.
or
The connection is already open.
试试这个 Code.May 很有帮助。
public void NewClass()
{
try
{
string query = "if exists(SELECT db_id('{0}'),'TEST') ";
query += "begin ";
query += "print 'All Ready Exists' ";
query += "end ";
query += "else ";
query += "begin ";
query += "create database TEST ";
query += "end ";
lblno.Text = query+"<br>";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
int ans = cmd.ExecuteNonQuery();
cmd.Cancel(); cmd.Dispose();
con.Close(); con.Dispose();
string table = "if exists (select OBJECT_ID('test')) begin ";
table += "print 'all ready' end ";
table += "else begin ";
table += "CREATE TABLE dbo.MyTable (ID int IDENTITY(1,1) PRIMARY KEY,MyProduct nvarchar(100) NOT NULL,MyDateTime datetime NOT NULL) ";
table += "end ";
con = new SqlConnection("Data Source=DESKTOP-0R1BJNQ\HARDIKPATEL;Initial Catalog=" + dbnm + ";Integrated Security=True");
con.Open();
cmd = new SqlCommand(table, con);
cmd.ExecuteNonQuery();
cmd.Cancel(); cmd.Dispose();
con.Close(); con.Dispose();
}
catch(Exception err)
{
lblmsg.Text = err.ToString();
}
}