简体   繁体   English

如何使用C#将数据插入MS访问?

[英]How to insert Data to MS access using C#?

I created a database in ms access, in the database I have a table with two columns, fist column is Name with Text data type, and the other column is Date with Date/time data type. 我创建在MS Access数据库,在数据库中我有一个表有两列,拳头列是NameText数据类型,另一列是DateDate/time数据类型。 and I want to insert values in the table, but it give this error for the month calendar 并且我想在表中插入值,但是它给月历提供了此错误

Data type mismatch in criteria expression. 条件表达式中的数据类型不匹配。

string sqlQuery = "INSERT INTO register (`Name`,`Date`) values (?,?)";

using (OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=E:\DB.accdb"))
using (OleDbCommand cmd = new OleDbCommand(sqlQuery, conn))
{
    conn.Open();
    cmd.Parameters.AddWithValue("@Name", this.textBox1.Text);
    cmd.Parameters.AddWithValue("@Date", this.monthCalendar1.Text);
    cmd.ExecuteNonQuery();
}

and the other column is Date with Date/time data type 另一列是“日期/时间”数据类型的“日期”

The problem is you try to insert this column a string which is this.monthCalendar1.Text . 问题是您尝试将此列插入为this.monthCalendar1.Text的字符串。 You need to pass the DateTime directly to it. 您需要直接DateTime 传递给它。

We don't know what this monthCalendar1 control exactly but it should have some SelectedDate property or something. 我们不知道这个monthCalendar1控件到底是什么,但是它应该具有某些SelectedDate属性或其他内容。 If does not have, just parse this string to DateTime with DateTime.Parse or something. 如果没有,只需使用DateTime.Parse或其他将其解析为DateTime

Do not use AddWithValue method. 不要使用AddWithValue方法。 It may generate unexpected and surprising results sometimes . 有时它可能会产生意外和令人惊讶的结果 Use Add method overloads to specify your parameter type and it's size. 使用Add方法重载来指定参数类型及其大小。

从AddwithValue括号中删除

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM