SqlCommand没有执行

时间:2016-03-14 12:46:18

标签: c# sql-server sqlconnection sqlcommand

我不明白为什么我的代码没有正确执行SqlCommand,即使我没有收到任何错误。

这是我的代码:

_connection.Connection.OpenAsync();
_connection.SqlCommand.Connection = _connection.Connection;
_connection.SqlCommand.CommandText = "insert into test (id, name) values ('dq1we3','d2qwe3')";
_connection.SqlCommand.ExecuteNonQueryAsync();
_connection.Dispose();

我在这里初始化SqlConnectionSqlCommand

private readonly string _conString = Settings.Default.RssConnectionString;

public SqlConnection Connection;
public SqlCommand SqlCommand;

public TestConnection()
{
    Connection = new SqlConnection(_conString);
    SqlCommand = new SqlCommand();
}

public void Dispose()
{
    Connection.Close();
}

2 个答案:

答案 0 :(得分:2)

应该做这样的事情:

using (var myConnection = new SqlConnection(connectionString)) // using automatically disposes of object
{
    myConnection.Open();

    string commandText = "insert into test (id, name) values ('dq1we3','d2qwe3')";

    using (var myCommand = new SqlCommand(commandText, myConnection))
    {
        myCommand.CommandType = CommandType.Text;
        myCommand.ExecuteNonQuery();
    }
}

答案 1 :(得分:0)

您需要在打开连接之前先设置连接字符串吗?

_connection.SqlCommand.Connection = _connection.Connection;
_connection.Connection.OpenAsync();