2015-12-22 44 views
1

我正在玩弄一个POC,并创建了以下电话。如何实际执行命令?

public string DoStuff() 
{ 
    try 
    { 
    using (SqlDataAdapter adapter = new SqlDataAdapter()) 
    { 
     SqlConnection connection = new SqlConnection("Server..."); 
     string command = "insert into Records values (...)"; 
     adapter.InsertCommand = new SqlCommand(command, connection); 
    } 
    } 
    catch (Exception exception) 
    { 
    return exception.Message + " " + exception.InnerException; 
    } 
    return "WeeHee!"; 
} 

我看到的文字是快乐的,所以我认为没有例外。因此,我得出结论:对数据库的调用按照预期执行。但是,数据库中没有创建新行。

我使用了与我在配置文件中相同的连接字符串,以及从SQL管理器中粘贴的命令,它在那里工作。

所以我的怀疑是,虽然我创建了一个插入命令,我从来没有真正执行它,但根据MSDN这就是它应该如何工作。

我在这里想念什么愚蠢的东西?

+3

adapter.InsertCommand.ExecuteNonQuery(); ? – Valentin

+0

@Valentin啊哈!我尝试了intellisensing for * execute *,但是我只在适配器上这样做。驴我!发布作为答复,所以我可以接受作为答案,请。 –

+0

connection.Open()也许。 – mecek

回答

2

你缺少connection.Open();adapter.InsertCommand.ExecuteNonQuery();

using (SqlDataAdapter adapter = new SqlDataAdapter()) 
{ 
    SqlConnection connection = new SqlConnection("Server..."); 
    connection.Open(); 
    string command = "insert into Records values (...)"; 
    adapter.InsertCommand = new SqlCommand(command, connection); 
    adapter.InsertCommand.ExecuteNonQuery(); 
} 
2

您应该改用ExecuteNonQuery。对INSERT查询使用SqlDataAdapter没有意义。

你也应该Open你的连接只是然后再执行它。

+0

真实的评论。但正如我所说:“*玩弄POC *”。这不是它将被长期使用。 –

1

您链接到的示例返回SQLAdapter供以后使用。

你不需要一个根本:

using (SqlConnection connection = new SqlConnection("Server...")) 
{ 
    string command = "insert into Records values (...)"; 
    connection.Open(); 
    var command = new SqlCommand(command, connection); 
    command.ExecuteNonQuery(); 
} 

注意,还有其他执行方法,这取决于预期的返回值以及是否要异步操作:https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand(v=vs.110).aspx

+0

保留答复,因为这对此任务确实很有价值。在我的情况下,我也会做其他的事情,所以它更适合,但是样本+1。无论如何,你很好地回答了实际问题。 :) –

1

您可以:

using(SqlConnection connection = new SqlConnection("Server...")) 
{ 
    SqlCommand command = connection.CreateCommand(); 
    command.CommandText = "insert into Records values (...)"; 
    connection.Open(); 
    int craeted = command.ExecuteNonQuery(); 
} 
+0

在你的回复中可以自由地改变一下。很好地制定,但+1。 –