我擦!!!终于搞定,用了大半天
在第一次用access的时候
1,排除了 access表不能插入
2,排除了是语法上的错误
3,检验 是写的SQL语句有问题
4,也排除了是数据库关键字的问题
5,注:填入的数据与数据库的数据的类型的必须一致
6. 必须得加“[ ]” ? string insertSQL = "INSERT INTO ProductDB" + " ([Product],[Price],[Number]) " + "VALUES (?,?,?)"; 有些是关键字,所以得加“[ ]”。
private void btnConfirm_Click(object sender, EventArgs e)
{
//建立数据库连接
using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;Data Source=D:\Personal\Desktop\Database6.mdb"))
{
try
{
/*
//操作数据库
// The insertSQL string contains a SQL statement that
// inserts a new row in the source table.
string insertSQL = "INSERT INTO ProductDB" + " ([Product],[Price],[Number]) " + "VALUES (?,?,?)";
OleDbCommand cmd= new OleDbCommand(insertSQL);
cmd.Parameters.Add("@Product", OleDbType.VarWChar, 30).Value = txtName.Text;
cmd.Parameters.Add("@Price", OleDbType.VarWChar, 30).Value = txtPrice.Text;
cmd.Parameters.Add("@Number", OleDbType.VarWChar, 30).Value = txtNum.Text;
// Set the Connection to the new OleDbConnection.
cmd.Connection = conn;
// Open the connection and execute the insert command.
try
{
conn.Open();
int i= cmd.ExecuteNonQuery();
if(i>0)
{
MessageBox.Show("添加失败");
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
// The connection is automatically closed when the
// code exits the using block.
}
catch (Exception EX)
{
MessageBox.Show("添加失败" + EX.ToString());
}
finally
{
//关闭数据库
conn.Close();
}
}
}
}
本文详细记录了在使用Access数据库时遇到的插入数据问题及解决过程。从排查表结构问题到确认SQL语句正确性,最终发现需为部分关键字字段添加方括号,并确保参数类型与数据库中定义的一致。
1770

被折叠的 条评论
为什么被折叠?



