我在连接到MS Access DB 2007时遇到问题。代码:
private void btnSave_Click(object sender, EventArgs e)
{
OleDbConnection Conn = new OleDbConnection();
try
{
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ Directory.GetCurrentDirectory() +"\\dvd_manager.accdb;Persist Security Info=False;";
Conn.ConnectionString = conn;
Conn.Open();
int i = cbbLocatie.SelectedIndex + 65;
char c = (char)i;
string sql = "INSERT INTO DVD (titel, locatie)VALUES(@titel, @locatie)";
OleDbCommand Com = new OleDbCommand();
Com.CommandText = sql;
Com.Connection = Conn;
OleDbParameter Param = new OleDbParameter("@titel", txtTitle.Text);
Com.Parameters.Add(Param);
Param = new OleDbParameter("@locatie", c);
Com.Parameters.Add(Param);
Com.ExecuteNonQuery();
Conn.Close();
MessageBox.Show("Data is opgeslagen " + sql);
}
catch (Exception ex)
{
MessageBox.Show("Fout opgetreden: " + ex.Message);
}
finally
{
Conn.Close();
}
}
当我运行此代码时,出现消息框。这应该意味着我的数据已插入。但是,当我打开accdb文件时,没有数据插入。我究竟做错了什么?
n
编辑:
ExecuteNonQuery()的返回值为1(我编辑我的帖子,因为我无法添加任何评论,所以当我单击“添加评论”时,该框不会显示。)
编辑2:
我用Title和Location属性创建了一个类。代码:
私有(private)无效btnSave_Click(对象发送者,EventArgs e)
{
OleDbConnection Conn =新的OleDbConnection();
try
{
string conn = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+ Directory.GetCurrentDirectory() +"\\dvd_manager.accdb;Persist Security Info=False;";
Conn.ConnectionString = conn;
// Create object
Medium M = new Medium();
int i = cbbLocatie.SelectedIndex + 65;
char c = (char)i;
M.Location = c;
M.Title = txtTitle.Text;
Conn.Open();
string sql = "INSERT INTO DVD (titel, locatie)VALUES(@titel, @locatie)";
OleDbCommand Com = new OleDbCommand();
Com.CommandText = sql;
Com.Connection = Conn;
OleDbParameter Param1 = new OleDbParameter("@titel", M.Title);
Com.Parameters.Add(Param1);
OleDbParameter Param2 = new OleDbParameter("@locatie", M.Location);
Com.Parameters.Add(Param2);
int ret = Com.ExecuteNonQuery();
Conn.Close();
MessageBox.Show("Data is opgeslagen " + ret);
}
catch (OleDbException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show("Fout opgetreden: " + ex.Message);
}
finally
{
Conn.Close();
}
}
由于我仍然无法单击添加注释按钮,因此这是带有无名sql参数的新代码:
// some code
Conn.Open();
string sql = "INSERT INTO DVD (titel, locatie)VALUES(?, ?)";
OleDbCommand Com = new OleDbCommand();
Com.CommandText = sql;
Com.Connection = Conn;
OleDbParameter Param1 = new OleDbParameter("@p1", OleDbType.VarChar, 1);
Param1.Value = M.Title;
Com.Parameters.Add(Param1);
OleDbParameter Param2 = new OleDbParameter("@p2", OleDbType.VarChar, 255);
Param2.Value = M.Location;
Com.Parameters.Add(Param2);
int ret = Com.ExecuteNonQuery();
Conn.Close();
// morde code
最佳答案
ExecuteNonQuery将返回一个int,指示受影响的行数。我要做的第一件事是检查退货。 ExecuteNonQuery可以执行并且不影响任何行,而不会触发捕获。
关于C#如何连接到MS Access 2007,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/508345/