繁体   English   中英

使用C#将数据插入MS Access表

[英]Inserting data into MS Access table using c#

谁能告诉我这段代码有什么问题吗? 提前致谢。

在此处输入图片说明

myConnection.ConnectionString = myConnectionString;
myConnection.Open();
OdbcCommand command = myConnection.CreateCommand();
command.CommandText = 
     "INSERT INTO Table1(type, from, to, depart, arrival, remain) VALUES(?, ?, ?, ?, ?, ?)";

TimeSpan time = new TimeSpan(10, 7, 00);
DateTime t = new DateTime(2016, 5, 5, 5, 4, 3);
command.Parameters.AddWithValue("@type", "test");
command.Parameters.AddWithValue("@from", "tet");
command.Parameters.AddWithValue("@to", "te");
command.Parameters.AddWithValue("@depart", t);
command.Parameters.AddWithValue("@arrival", t);
command.Parameters.AddWithValue("@remain", 4);

command.ExecuteNonQuery();

您正在使用Access保留字 type并将from作为表中的列名。

这可能是您收到此类错误的原因。

您可以使用方括号将此类列名称包装起来,然后将命令文本更改为:

INSERT INTO Table1([type], [from], to, depart, arrival, remain) VALUES(?, ?, ?, ?, ?, ?)

这是为Web应用程序插入功能编写的代码:

编码:

    string dataPath = Server.MapPath("Your DataPath");
    string ConString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + dataPath + ";Persist Security Info=True";            
    OleDbConnection Con = new OleDbConnection(ConString);
    OleDbCommand Command = Con.CreateCommand();
    Con.Open();
    Command.CommandText = "Insert into Table1(type, from, to, depart, arrival, remain) Values (@type, @from, @to, @depart, @arrival, @remain);      
    TimeSpan time = new TimeSpan(10, 7, 00);
    DateTime t = new DateTime(2016, 5, 5, 5, 4, 3);
    command.Parameters.AddWithValue("@type", "test");
    command.Parameters.AddWithValue("@from", "tet");
    command.Parameters.AddWithValue("@to", "te");
    command.Parameters.AddWithValue("@depart", t);
    command.Parameters.AddWithValue("@arrival", t);
    command.Parameters.AddWithValue("@remain", 4);
    command.ExecuteNonQuery();
    Con.Close();

暂无
暂无

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

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