尝试与SQL Server 2008建立连接

时间:2012-10-22 08:18:04

标签: asp.net sql-server-2008

SqlConnection cnn = new SqlConnection();
cnn.ConnectionString = "Data Source=.;Database = deptStore;Integrated Security = true;";

cnn.Open();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "insert into Employee values('" + TextBox1.Text + "','" + TextBox2.Text + "','" + TextBox3.Text + "','" + TextBox4.Text + "','" + TextBox5.Text + "','" + TextBox6.Text + "','" + TextBox7.Text + "','" + TextBox8.Text + "','" + TextBox9.Text + "','" + TextBox10.Text + "','" + TextBox11.Text + "','" + TextBox12.Text + "','" + TextBox13.Text + "')";
cmd.Connection = cnn;

cmd.ExecuteNonQuery();

Response.Write("Record Save");
cnn.Close();

但我收到以下错误:

  

SqlException未被用户代码

处理      

发生与网络相关或特定于实例的错误   建立与SQL Server的连接。找不到服务器或   无法访问。验证实例名称是否正确   SQL Server配置为允许远程连接。 (提供者:命名   管道提供程序,错误:40 - 无法打开与SQL Server的连接)

请帮助我理解错误并纠正错误。

2 个答案:

答案 0 :(得分:0)

您是否验证过SQL Server配置正确?您可以通过打开SQL Server配置工具来执行此操作。

如果您要连接到SQL Server Express,则需要在连接字符串中指定始终为SQLExpress的实例的名称。

I.e

Data Source=.\SQLEXPRESS"...

答案 1 :(得分:0)

首先检查您的webconfig。应该有这样的代码

<connectionStrings>
<add name="ConnStringDb1" connectionString="Data Source=localhost;Initial Catalog=deptStore;Integrated Security=True;" providerName="System.Data.SqlClient" />

或者如果您只想替换YourDataBaseName。 接下来是设置连接

SqlConnection con = new SqlConnection(WebConfigurationManager.ConnectionStrings["ConnStringDb1"].ToString());

就是这样,你有一个连接字符串

您需要阅读有关此原因的更多信息我还会看到您的插入查询错误

试试这个

cnn.ConnectionString =“Data Source = localhost; Database = deptStore; Integrated Security = true;”;

相关问题