如何使用oledb将记录插入访问表?
我在ms访问中有一个这个Items表
Items(Table) Item_Id(autonumber) Item_Name(text) Item_Price(currency)
我正在尝试使用此代码插入记录。
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString()); OleDbCommand cmd = new OleDbCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values ('" + itemNameTBox.Text + "','" + Convert.ToDouble(itemPriceTBox.Text) + "')"; cmd.Connection = myCon; myCon.Open(); cmd.ExecuteNonQuery(); System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); myCon.Close();
代码运行没有错误,但最后没有在表中找到记录我正在做什么错误?
您的sql插入文本不使用参数。
这是错误和更糟的原因(SqlInjection)
以这种方式更改您的代码;
using(OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString())) { OleDbCommand cmd = new OleDbCommand(); cmd.CommandType = CommandType.Text; cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values (?,?); cmd.Parameters.AddWithValue("@item", itemNameTBox.Text); cmd.Parameters.AddWithValue("@price", Convert.ToDouble(itemPriceTBox.Text)); cmd.Connection = myCon; myCon.Open(); cmd.ExecuteNonQuery(); System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information); }
当然,这假设price的文本框包含正确的数值。
在调用上面的代码之前,请务必添加此行
double price; if(double.TryParse(itemPriceTBox.Text, out price) == false) { MessageBox.Show("Invalid price"); return; }
然后使用price
作为参数@price
值
**编辑4年后**
这个答案需要更新。 在上面的代码中,我使用AddWithValue将参数添加到Parameters集合中。 它的工作原理但应该告诉每个读者AddWithValue有一些缺点。 特别是如果您在目标列期望十进制值或日期时为简单路径添加字符串。 在这种情况下,如果我写的只是
cmd.Parameters.AddWithValue("@price", itemPriceTBox.Text);
结果可能是语法错误或某种奇怪的值转换,日期可能会发生同样的情况。 AddWithValue创建一个字符串Parameter,数据库引擎应该将值转换为预期的列类型。 但是客户端和服务器之间的区域设置差异可能会对值产生任何误解。
我认为使用它总是更好
cmd.Parameters.Add("@price", OleDbType.Decimal).Value = Convert.ToDecimal(itemPriceTBox.Text);
有关AddWithValue问题的更多信息, 请点击此处