Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/331.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用OleDbDataAdapter插入Access数据库_C#_Ms Access_Oledbdataadapter - Fatal编程技术网

C# 使用OleDbDataAdapter插入Access数据库

C# 使用OleDbDataAdapter插入Access数据库,c#,ms-access,oledbdataadapter,C#,Ms Access,Oledbdataadapter,我想在Access数据库中插入一些数据 DataTable dt = new DataTable(); String sql = string.Format("SELECT * FROM {0} where 1=0; ", tmap.SqlTableName); string con = string.Format(conn, accessPath); OleDbDataAdapter da = new OleDbDataAdapter(sql, con); OleDbCommandBuilde

我想在Access数据库中插入一些数据

DataTable dt = new DataTable();
String sql = string.Format("SELECT * FROM {0} where 1=0; ", tmap.SqlTableName);
string con = string.Format(conn, accessPath);
OleDbDataAdapter da = new OleDbDataAdapter(sql, con);
OleDbCommandBuilder cmdBuilder = new OleDbCommandBuilder(da);
da.InsertCommand = cmdBuilder.GetInsertCommand(true); // Returns "INSERT INTO test (int, bdate, amt, text, bit) VALUES (?, ?, ?, ?, ?)"
da.Fill(dt);
//Add data to the DateTable
for (int i = 0; i < rowCount; i++)
{
DataRow dr = dt.NewRow();
//....
dt.Rows.Add(dr);
}
da.Update(dt); //This is where things go south.
并将传入数据更改为只有一个文本值:

没有为一个或多个必需参数提供值

我错过什么了吗

  • 确保插入查询中包含所有必需的列
  • 如果不起作用,则创建一个新的插入方法,并按照以下步骤操作:

    OLEDB连接连接=新的OLEDB连接(连接字符串)


  • 问题在于数据类型。如果数据类型兼容,则问题中的代码有效。

    1。我删除了数据库中除文本以外的所有列。没有骰子。2.这就是我以前做的。。。但是access数据库中有150多个表,它们将发生变化。所以我一直在寻找一种简单的方法,尽可能地保持活力。命令生成器看起来像是一个很好的自动匹配。但它似乎对插入不起作用。看起来我必须为这一个运行我自己的sql构建器。da.Update(dt)不应该在for循环中,即{}中吗?在for循环中移动da.Update(dt)只会在每次添加行时创建到数据库的新连接,对吗?--无论如何,移动它对主要问题没有帮助。你在循环之外打开了连接,所以我不知道为什么更新会创建新连接。当然,您使用的是一种我一无所知的技术(oledbdataadapter)。在Jet/ACE使用的常用数据访问库中,您必须单独更新每一行,即不能批处理更新。但可能您使用的工作方式不同,默认情况下是成批的。也许这就是它通常用于服务器后端的方式,而不适用于Jet/ACE。我只是在猜测。@David W.Fenton——问题在于数据类型。我最终使用了自己的命令生成器来实现这一点。
    da.InsertCommand = new OleDbCommand("INSERT INTO test ([text]) VALUES (?)");  
    
    OleDbCommand command = new OleDbCommand();
    command.Connection = conn;
    command.CommandText= "INSERT INTO myTable (col1, col2) VALUES (@p_col1, @p_col2)";
    command.Parameters.Add ("@p_col1", OleDbType.String).Value = textBox1.Text;
    ...
    command.ExecuteNonQUery();