[英]Connecting to local SQL Server database using C#
Suppose I have created a SQL Server database called Database1.mdf
in the App_Data
folder in Visual Studio with a table called Names
.假设我在 Visual Studio 的
App_Data
文件夹中创建了一个名为Database1.mdf
的 SQL 服务器数据库,其中包含一个名为Names
的表。
How could I establish a connection to read the table values using C#?我如何建立连接以使用 C# 读取表值?
So far I've tried something like this:到目前为止,我已经尝试过这样的事情:
SqlConnection conn = new SqlConnection("Server=localhost;Database=Database1;");
conn.Open();
// create a SqlCommand object for this connection
SqlCommand command = conn.CreateCommand();
command.CommandText = "Select * from Names";
But I get an error:但我得到一个错误:
database not found/error connecting to database
未找到数据库/连接到数据库时出错
In Data Source
(on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard
. 在
Data Source
(Visual Studio左侧)中右键单击数据库,然后单击“ Configure Data Source With Wizard
。 A new window will appear, expand the Connection string, you can find the connection string in there 将出现一个新窗口,展开Connection字符串,您可以在其中找到连接字符串
If you use SQL authentication , use this: 如果使用SQL身份验证 ,请使用以下命令:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"User Id=UserName;" +
"Password=Secret;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
If you use Windows authentication , use this: 如果使用Windows身份验证 ,请使用以下命令:
using System.Data.SqlClient;
SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Data Source=.\SQLExpress;" +
"User Instance=true;" +
"Integrated Security=true;" +
"AttachDbFilename=|DataDirectory|Database1.mdf;"
conn.Open();
SqlConnection c = new SqlConnection(@"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");
If you're using SQL Server express, change 如果您使用的是SQL Server Express,请进行更改
SqlConnection conn = new SqlConnection("Server=localhost;"
+ "Database=Database1;");
to 至
SqlConnection conn = new SqlConnection("Server=localhost\SQLExpress;"
+ "Database=Database1;");
That, and hundreds more connection strings can be found at http://www.connectionstrings.com/ 可以在http://www.connectionstrings.com/找到数百个连接字符串。
您尝试使用此字符串连接
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;
Visual Studio 2019 (and probably a few previous versions). Visual Studio 2019(可能还有几个以前的版本)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.