代码之家  ›  专栏  ›  技术社区  ›  NitroxDM

使用OleDbDataAdapter插入到访问数据库中

  •  0
  • NitroxDM  · 技术社区  · 16 年前

    我想在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.
    

    system.data.oledb.oledbexception(系统数据.oledb.oledbexception)
    消息:INSERT INTO语句语法错误。
    来源:Microsoft Jet数据库引擎。

    如果我更改了insert命令:

    da.InsertCommand = new OleDbCommand("INSERT INTO test ([text]) VALUES (?)");  
    

    并将传入数据更改为只有一个文本值:

    没有为一个或多个必需参数指定值。

    我错过什么了吗?

    2 回复  |  直到 16 年前
        1
  •  1
  •   NitroxDM    16 年前

    问题出在数据类型中。如果数据类型兼容,则问题中的代码可以工作。

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

      oledbconnection conn=新建oledbconnection(connectionString);

      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();
      
    推荐文章