使用 C# 连接到本地 SQL Server 数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12220865/
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
Connecting to local SQL Server database using C#
提问by Tony
Suppose I have created a SQL Server database called Database1.mdfin the App_Datafolder in Visual Studio with a table called Names.
假设我在 Visual StudioDatabase1.mdf的App_Data文件夹中创建了一个 SQL Server 数据库,其中有一个名为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
未找到数据库/连接到数据库时出错
采纳答案by Mohamad Y. Dbouk
In Data Source(on the left of Visual Studio) right click on the database, then Configure Data Source With Wizard. A new window will appear, expand the Connection string, you can find the connection string in there
在Data Source(在 Visual Studio 的左侧)右键单击数据库,然后Configure Data Source With Wizard. 将出现一个新窗口,展开连接字符串,您可以在其中找到连接字符串
回答by Aghilas Yakoub
You try with this string connection
你试试这个字符串连接
Server=.\SQLExpress;AttachDbFilename=|DataDirectory|Database1.mdf;Database=dbname; Trusted_Connection=Yes;
回答by David
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/找到数百个连接字符串
回答by czuroski
回答by Hassan Boutougha
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();
回答by ablaze
SqlConnection c = new SqlConnection(@"Data Source=localhost;
Initial Catalog=Northwind; Integrated Security=True");

