建立连接和查询到SQL Server Express数据库的正确方法 [英] Proper way to make a connection and query to a SQL Server Express database

查看:338
本文介绍了建立连接和查询到SQL Server Express数据库的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个示例C#(控制台应用程序)代码连接到SQL Server Express数据库
并将一些变量插入表laptops

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"


  • SQL Server Express是@ localhost

  • 用户名是数据库

  • ,密码是testdatabase

这样做的正确方法是什么?

What is the proper way to do that ?

推荐答案

基本ADO.NET 101:

Basic ADO.NET 101:


  • 设置连接

  • 设置命令以执行某些操作

  • 执行该命令

步骤1:设置连接

您需要知道数据库的连接字符串。请查看 http://www.connectionstrings.com 了解的示例。

You need to know the connection string to your database. Check out http://www.connectionstrings.com for a ton of examples.

在你的情况下,你说它是一个本地SQL Server Express实例 - 但不幸的是,你没有提到你的数据库。 ...您的连接字符串将是:

In your case, you say it's a local SQL Server Express instance - but unfortunately, you didn't mention what your database is called..... your connection string will be something like:

server=(local)\SQLEXPRESS;database=YourDatabaseName;user id=database;pwd=testdatabase

步骤2:设置命令

您可以使用各种命令 - 选择数据,删除数据或插入数据。无论您做什么 - 我建议始终使用参数化查询以避免SQL注入。

You can have various commands - to select data, to delete that, or to insert data. Whatever you do - I would recommend to always use parametrized queries to avoid SQL injection.

因此,您的代码看起来像: p>

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

这篇关于建立连接和查询到SQL Server Express数据库的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆