C# - SQLClient - 最简单的插入
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
C# - SQLClient - Simplest INSERT
提问by Brian Warshaw
I'm basically trying to figure out the simplest way to perform your basic insert operation in C#.NET using the SqlClient namespace.
我基本上是想找出使用 SqlClient 命名空间在 C#.NET 中执行基本插入操作的最简单方法。
I'm using SqlConnection
for my db link, I've already had success executing some reads, and I want to know the simplest way to insert data. I'm finding what seem to be pretty verbose methods when I google.
我正在使用SqlConnection
我的数据库链接,我已经成功执行了一些读取,我想知道插入数据的最简单方法。当我谷歌时,我发现似乎很冗长的方法。
采纳答案by Matt Hamilton
using (var conn = new SqlConnection(yourConnectionString))
{
var cmd = new SqlCommand("insert into Foo values (@bar)", conn);
cmd.Parameters.AddWithValue("@bar", 17);
conn.Open();
cmd.ExecuteNonQuery();
}
回答by aku
using (SqlConnection myConnection new SqlConnection("Your connection string"))
{
SqlCommand myCommand = new SqlCommand("INSERT INTO ... VALUES ...", myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
}
回答by AlexCuse
Since you seem to be just getting started with this now is the best time to familiarize yourself with the concept of a Data Access Layer (obligatory wikipedia link). It will be very helpful for you down the road when you're apps have more interaction with the database throughout and you want to minimize code duplication. Also makes for more consistent behavior, making testing and tons of other things easier.
由于您现在似乎刚刚开始使用它,因此现在是熟悉数据访问层概念的最佳时机(强制性维基百科链接)。当您的应用程序在整个过程中与数据库进行更多交互并且您希望最大程度地减少代码重复时,它将对您非常有帮助。还可以使行为更加一致,使测试和大量其他事情变得更容易。