【发布时间】:2015-07-30 15:13:11
【问题描述】:
System.Data.dll 中出现“System.Data.SqlClient.SqlException”类型的未处理异常
其他信息:在建立与 SQL Server 的连接时发生与网络相关或特定于实例的错误。服务器未找到或无法访问。验证实例名称是否正确以及 SQL Server 是否配置为允许远程连接。 (提供者:命名管道提供者,错误:40 - 无法打开与 SQL Server 的连接)
我使用了这些代码:
public partial class Form1 : Form
{
SqlConnection con = new SqlConnection();
public Form1()
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
// TODO: This line of code loads data into the 'sTUDENTDataSet.login' table. You can move, or remove it, as needed.
//this.loginTableAdapter.Fill(this.sTUDENTDataSet.login);
SqlConnection con = new SqlConnection("Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True");
con.Open();
{
}
}
private void btnLogin_Click_1(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
con.Open();
string UserId = txtUsername.Text;
string UserPass = txtPassword.Text;
SqlCommand cmd = new SqlCommand("Select UserId,UserPass from Login where UserId='" + txtUsername.Text + "'and UserPass='" + txtPassword.Text + "'", con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
DataTable dt = new DataTable();
da.Fill(dt);
if (dt.Rows.Count > 0)
{
MessageBox.Show("Login sucess!");
Form2 form = new Form2();
form.Show();
}
else
{
MessageBox.Show("Invalid Login Information. Please check username and password");
}
con.Close();
}
这里的错误是属于这里的con.Open();:
SqlConnection con = new SqlConnection();
con.ConnectionString = "Data Source=SQLEXPRESS;Initial Catalog=StudentInformation;Integrated Security=True";
con.Open();
我尝试删除它,因为我不知道还能做什么,第二个错误出现在 da.Fill(dt); 上,所以我想真正应该修复的唯一问题是 con.Open();
我该怎么办?
【问题讨论】:
-
如果您在 localhost 中运行此代码,请尝试将数据源更改为:localhost\SQLEXPRESS 并验证目录名称是否正确。
-
看起来数据库在你的本地机器上。尝试使用 SQL Server Management Studio 和 Windows 身份验证连接到该数据库服务器。我觉得主机名不正确。如果正确,请检查所有 SQL Server 服务是否已启动并运行。
-
'SqlConnection con = new SqlConnection(); con.ConnectionString = "本地主机=SQLEXPRESS;初始目录=StudentInformation;集成安全=True"; con.Open();'它说不支持本地主机
-
请将 SQLEXPRESS 更改为点 (.) 或 localhost,然后反馈给我们
标签: c# sql-server visual-studio login sqlconnection