使用c#

时间:2016-11-01 12:05:08

标签: c# sql ms-access insert odbc

任何人都可以告诉我这段代码有什么问题吗?提前谢谢。

enter image description here

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();

2 个答案:

答案 0 :(得分:2)

您在表格中使用Access reserved words typefrom作为列名。

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

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

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

答案 1 :(得分:0)

这是对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();