我需要使用C#在Access 2000数据库中插入记录。代码在SqlConnection上失败。请帮忙。
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Trading.mdb";
string commandText = "INSERT INTO Order (OpenDate) VALUES (@OpenDate)";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.AddWithValue("@OpenDate", DateTime.Now);
try
{
command.Connection.Open();
int response = command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: {0}" + ex.Message);
}
}
答案 0 :(得分:3)
问题:您正在使用MS-Access数据库,但使用的是SqlServer对象。
解决方案:您需要使用OleDbConnection
对象而不是SqlConnection
和OleDbCommand
代替SqlCommand
试试这个:
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Trading.mdb";
string commandText = "INSERT INTO Order (OpenDate) VALUES (?)";
using (OleDbConnection connection = new OleDbConnection(connectionString))
{
OleDbCommand command = new OleDbCommand(commandText, connection);
command.Parameters.AddWithValue("@OpenDate", DateTime.Now);
try
{
command.Connection.Open();
int response = command.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Error: {0}" + ex.Message);
}
}
答案 1 :(得分:2)
您需要OleDbConnection而不是SqlConnection
用于SQL Server。