gpt4 book ai didi

sql - 在 Visual C# 中连接到 SQL Server

转载 作者:搜寻专家 更新时间:2023-10-30 23:47:33 24 4
gpt4 key购买 nike

我将展示我正在使用的代码,但我无法通过 Visual C# 连接到 SQL Server。我已经安装了 C# 包中的内容,但我不断收到此错误:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

我不知道如何连接到服务器。我正在使用 Windows 8、SQL Sever 2012 (Visual Studio 2012),如果我在顶部工具栏中进行连接,使用(本地)、本地主机或我的 IP 地址都没有关系。我想不通,这让我发疯!这是我的代码,如果有帮助的话。

private void btnSave_Click(object sender, EventArgs e)
{
System.Data.SqlClient.SqlConnection sqlConnection1 =
new System.Data.SqlClient.SqlConnection("Server=(local);Database=Database1DataSet;Trusted_Connection=True;");

System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand();
cmd.CommandType = System.Data.CommandType.Text;
cmd.CommandText = "INSERT VALUES (id, Medname, MedDose, MedAm, MedNoon, MedEve, MedNight, MedPRN, MedOther) VALUES (1, 'Clonazepam', '2mg', 'true', 'true', 'false', 'true', 'true', 'false')";
cmd.Connection = sqlConnection1;

sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}

非常感谢。这是我第一次通过 Visual Studio 使用 SQL Server。

最佳答案

如果您在 Visual Studio 2012 安装过程中安装了 SQL Server,则它会安装 SQL Server Express LocalDB。 LocalDB 非常轻量级,没有持续运行的服务。如果您在安装 Visual Studio 时确实安装了 LocalDB,您应该能够通过转到 Visual Studio 中的View 菜单并选择SQL Server Object Explorer 来查看“实例” .应该有一个用于“SQL Server”的文件夹(可以这么说)并展开它应该会向您显示以下内容:

(localdb)\V11
或者
(localdb)\Projects

无论该值是什么,这就是您在连接字符串中为“server=”指定的值。因此,您的连接字符串应该看起来更像这样(由于反斜杠,您应该在字符串前加上 @):

@"Server=(localdb)\V11;Database=Database1DataSet;Trusted_Connection=True;"

此外,当您在 Visual Studio 中创建新项目时,它应该在 Project PropertiesDebug 选项卡中预填充正确的连接字符串。

编辑:
此外,您可以在以下位置找到实例名称,因为每个实例都是一个子文件夹:

C:\Users\{YourUserName}\AppData\Local\Microsoft\Microsoft SQL Server Local DB\Instances

关于sql - 在 Visual C# 中连接到 SQL Server,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26477242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com