我可以使用SQL Server连接字符串在c#中创建OleDbConnection对象吗?如果是,我需要使用什么提供商?如果可能的话,任何示例代码都会有所帮助。
您必须将SqlConnectionStringBuilder的参数解析为OleDbConnectionStringBuilder:
System.Data.OleDb.OleDbConnectionStringBuilder builder =
new System.Data.OleDb.OleDbConnectionStringBuilder();
builder["Provider"] = "Microsoft.Jet.OLEDB.4.0";
builder["Data Source"] = "C:\Sample.mdb";
builder["User Id"] = "Admin;NewValue=Bad";
var connectionString = builder.ConnectionString;
并创建连接:
public void InsertRow(string connectionString, string insertSQL)
{
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
OleDbCommand command = new OleDbCommand(insertSQL);
// Set the Connection to the new OleDbConnection.
command.Connection = connection;
// Open the connection and execute the insert command.
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
}
来源于Microsoft文档