SqlCommand

时间:2016-10-08 03:47:52

标签: c# wpf sql-server-2016

我以编程方式创建数据库,然后在数据库中创建一个表。创建数据库,但不创建表。

// 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());
}

但是我收到错误消息,说我的连接没有关闭。

enter image description here

我尝试重复添加sqlConn.Close()到每个{block}的结尾但仍然得到相同的错误。如何在创建数据库后正确关闭连接,然后再次重新打开连接以创建表?

[编辑]

在输入答案后,我重构了我的代码,我确信包装属性而不重复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时,表格不存在。我现在很困惑。

enter image description here

3 个答案:

答案 0 :(得分:5)

当您去创建表时,您尝试两次打开连接。 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

     

如果未指定数据源或服务器,则无法打开连接   或
  连接已经打开。

答案 1 :(得分:1)

我没有看到您关闭第二个查询的连接。您可以使用 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(...);
}

答案 2 :(得分:0)

试试此代码。可能会有帮助。

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();
    }
}