从c#“插入”accdb

时间:2015-02-04 20:34:22

标签: c# ms-access insert-into

我在c#中写了这两个代码来写一个访问accdb的行,但它们不兼容:

String tableName = "ARE";
                String query = String.Format(
                              "select * from [{0}]", tableName);
                DataSet ds = new DataSet();
                using (OleDbConnection conn =
                      new OleDbConnection(connection_string))
                {
                    try
                    {
                        //Open Database Connection
                        conn.Open();
                        OleDbDataAdapter da =
                               new OleDbDataAdapter(query, conn);
                        OleDbCommandBuilder cmdB =
                               new OleDbCommandBuilder(da);
                        da.MissingSchemaAction =
                               MissingSchemaAction.AddWithKey;

                        //Fill the DataSet
                        da.Fill(ds, tableName);

                        DataRow row = ds.Tables["ARE"].NewRow();
                        row["ID"] = "1";
                        row["Localizzazione"] = "1";
                        row["UO"] = "UO1";
                        row["Coordinate"] = "333;336";

                        ds.Tables["ARE"].Rows.Add(row);
                        da.Update(ds, "ARE");

                    }
                    catch (OleDbException exp)
                    {
                        MessageBox.Show("Database Error:" + exp.Message.ToString());
                    }

 using (OleDbConnection oc = new OleDbConnection(connection_string))
                {

                    string q = "INSERT INTO ARE "
                                + "(ID, Localizzazione, UO, Coordinate) "
                                + "VALUES (@ID, @Localizzazione, @UO, @Coordinate)";

                    OleDbCommand insertCommand = new OleDbCommand(q, oc);

                    insertCommand.Parameters.Add("@ID", OleDbType.Integer).Value = 1;
                    insertCommand.Parameters.Add("@Localizzazione", OleDbType.Integer).Value = 1;
                    insertCommand.Parameters.Add("@UO", OleDbType.Char).Value = (UO[selectedUO])[1].ToString();
                    insertCommand.Parameters.Add("@Coordinate", OleDbType.Char).Value = (e.X - 12) + ";" + (e.Y - 12);

                    oc.Open();
                    insertCommand.ExecuteNonQuery();

                }

但总是告诉我“错误sintax on isctruction INSERT INTO。” System.Data.OleDb.OleDbException

WHY ??? :(

2 个答案:

答案 0 :(得分:2)

' ARE'根据{{​​3}},是Jet数据库引擎的保留关键字。您现在可以使用方括号来解决此问题(例如INSERT INTO [ARE],但您应该考虑更改表名。

答案 1 :(得分:0)

为什么要声明字符串q然后字符串q?看起来你的sql写得不正确..空格,大写等等。