C# 连接和查询 SQL Server Express 数据库的正确方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9348148/
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
Proper way to make a connection and query to a SQL Server Express database
提问by Axxess
I need a sample C# (console application) code witch connects to an SQL Server Express database and inserts a few variables into a table "laptops"
我需要一个示例 C#(控制台应用程序)代码女巫连接到 SQL Server Express 数据库并将一些变量插入表“笔记本电脑”
- SQL Server Express is @ localhost
- user name is database
- and password is testdatabase
- SQL Server Express 是@localhost
- 用户名是数据库
- 密码是 testdatabase
What is the proper way to do that ?
这样做的正确方法是什么?
采纳答案by marc_s
Basic ADO.NET 101:
基本的 ADO.NET 101:
- set up a connection
- set up a command to do something
- execute that command
- 建立连接
- 设置一个命令来做某事
- 执行那个命令
Step 1: setting up a connection
第一步:建立连接
You need to know the connection string to your database. Check out http://www.connectionstrings.comfor a tonof examples.
您需要知道数据库的连接字符串。查看http://www.connectionstrings.com以获取大量示例。
In your case, you say it's a local SQL Server Express instance - but unfortunately, you didn't mention what your databaseis called..... your connection string will be something like:
在你的情况下,你说它是一个本地 SQL Server Express 实例 - 但不幸的是,你没有提到你的数据库叫什么......你的连接字符串将是这样的:
server=(local)\SQLEXPRESS;database=YourDatabaseName;user id=database;pwd=testdatabase
Step 2: setting up a command
第 2 步:设置命令
You can have various commands - to select data, to delete that, or to insert data. Whatever you do - I would recommend to alwaysuse parametrized queries to avoid SQL injection.
您可以使用各种命令 - 选择数据、删除数据或插入数据。无论您做什么 - 我都建议您始终使用参数化查询来避免 SQL 注入。
So your code here would look something like:
所以你在这里的代码看起来像:
string connectionString = "server=(local)\SQLEXPRESS;database=YourDatabaseName;user id=database;pwd=testdatabase";
string insertStmt = "INSERT INTO dbo.Laptops(Name, Model, ScreenSize) " +
"VALUES(@Name, @Model, @Screensize)";
using(SqlConnection conn = new SqlConnection(connectionString))
using(SqlCommand cmd = new SqlCommand(insertStmt, conn))
{
// set up the command's parameters
cmd.Parameters.Add("@Name", SqlDbType.VarChar, 100).Value = "ASUS SX30";
cmd.Parameters.Add("@Model", SqlDbType.VarChar, 50).Value = "Ultralight";
cmd.Parameters.Add("@Screensize", SqlDbType.Int).Value = 15;
// open connection, execute command, close connection
conn.Open();
int result = cmd.ExecuteNonQuery();
conn.Close();
}

