我正在使用这个简单的代码来打开与数据源的连接
using System.Data.SqlClient;
namespace DBOApplication
{
public partial class Form1 : Form
{
SqlConnection scon;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
scon = new SqlConnection();
scon.ConnectionString = "User Id=sa;Password=123;Database=MyTest;Data Source=CHARANSAHITHCHO\\REATIMEDB";
scon.Open();
MessageBox.Show(scon.State.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
scon.Close();
MessageBox.Show(scon.State.ToString());
this.Close();
}
}
}
当我运行此代码时,它对我来说很好,我能够打开一个连接。但是当我在app.config中放置连接字符串并在代码中使用它时,问题就出现了,如下所示
using System.Data.SqlClient;
using System.Configuration;
namespace DBOApplication
{
public partial class Form1 : Form
{
SqlConnection scon;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["SConStr"].ConnectionString;
scon = new SqlConnection(constr);
scon.Open();
MessageBox.Show(scon.State.ToString());
}
private void button2_Click(object sender, EventArgs e)
{
scon.Close();
MessageBox.Show(scon.State.ToString());
this.Close();
}
}
}
的app.config
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="SConStr" connectionString="User Id=sa;Password=123;Database=MyTest;Data Source=CHARANSAHITHCHO\\REATIMEDB" providerName="SqlOledb" />
</connectionStrings>
但在第二种情况下我得到实例失败错误
先谢谢
答案 0 :(得分:3)
正如已经提到的那样,从MSSQL实例名称中删除了额外的斜杠。
此外,您在连接字符串中使用SqlOleDb提供程序,但使用的是SqlClient(您的硬编码引用未指定)。将提供程序更改为:System.Data.SqlClient
另外,不要忘记在using语句中打开连接开头以确保它被彻底处理掉:)
using(var conn = new SqlConnection("blah"))
{
//do db stuff
}