我使用以下代码将C#与数据库连接
string connStr = "Provider=.NET Framework Data Provider for SQL Server"+
" Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True";
try
{
using (OleDbConnection conn = new OleDbConnection(connStr))
{
conn.Open();
if (conn.State == ConnectionState.Open)
{
using (OleDbCommand cmd = new OleDbCommand(selected_querry, conn))
{
cmd.CommandType = CommandType.Text;
using (OleDbDataAdapter dAdapter = new OleDbDataAdapter(selected_querry, conn))
{
DataSet ds = new DataSet();
try
{
dAdapter.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
}
catch (Exception)
{
MessageBox.Show("Error: Failed to Fill the required data Field from the DataBase.");
return;
}
}
}
}
else
MessageBox.Show("Connection Not Open");
}
}
catch (Exception e)
{
MessageBox.Show("Error: Failed to retrieve the required data from the DataBase."+e);
return;
}
当我运行代码时,我总是会收到以下错误
Provider for SQL Server is not Register On Local Machine
答案 0 :(得分:1)
使用OleDb连接,您需要在连接字符串中指定OLE DB提供程序而不是.NET提供程序,并指定OLE DB连接字符串关键字Server(而不是Data Source)和Trusted_Connection = yes(而不是Integrated Security) = SSPI):
string connStr = "Provider=SQLNCLI11.1"+
";Server=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\\Database1.mdf;Trusted_Connection=Yes";
SQL Server OLE DB提供程序包括:
但是,在.NET应用程序中,最好使用托管提供程序。对于SQL Server,SQL Server的.NET Framework数据提供程序(a.k.a SqlClient)将表现更好,尤其是对于大型结果集。使用SqlConnection,SqlCommand等,并从连接字符串中省略提供程序,因为它是隐式的。如果删除Provider规范,则连接字符串应该有效。