大家晚上好,
我正在尝试使用C#从SQL Server 2012数据库连接。当我使用SQL Server Management Studio时,我的连接设置如下:
Server Type: Database Engine
Server Name: Paul-PC\SQLEXPRESS
Authentication: Windows Authentication
Username: Greyed out
Password: Greyed out
我试图连接的数据库名称是"testDB"。
这是我的代码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace DatabaseConnection
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btnConnect_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("server=localhost;" +
"Trusted_Connection=yes;" +
"database=testDB; " +
"connection timeout=30");
try
{
myConnection.Open();
MessageBox.Show("Well done!");
}
catch(SqlException ex)
{
MessageBox.Show("You failed!" + ex.Message);
}
}
}
}
很遗憾,我的代码连接失败,并出现以下错误:
"You failed!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."
有什么建议吗?SQL Server正在本地运行。
(local)
而不是localhost
,是否会出现相同的错误?server=(local)\\SQLEXPRESS
会发生什么?另外,您确定您正在使用Paul-PC
吗? - Scott Chamberlain