简体   繁体   中英

C# inserting to SQL with ODBC connection syntax error

I want to insert rows every interval in c#. I'm getting this error:

[42000][Microsoft][ODBC SQL Server Driver][SQL Server] incorrect syntax near ';'.

Here is the code:

cmdString = $"INSERT INTO {n}" + "VALUES (?, ?);";
using (OdbcCommand comm = new OdbcCommand())
{
    comm.Connection = connection;
    comm.CommandText = cmdString;
    comm.Parameters.Add("value", System.Data.Odbc.OdbcType.Int).Value = value;
    comm.Parameters.Add("time", System.Data.Odbc.OdbcType.DateTime).Value = System.DateTime.Now;
    comm.ExecuteNonQuery();
    rows += 1;
}

please help

EDIT

Now everything seems to be ok, but I can't see the rows appear in the tables in sql server :/ Can you please help me with that too? here is my connectionstring:

connetionString = "Driver={Sql Server}; Server=baxu\\sqlexpress; Database = baza1;" + $"UID ={ username };PWD={ password };";

Your command string is false, missing space before values. So, instead of

cmdString = $"INSERT INTO {n}" + "VALUES (?, ?);";

do this:

cmdString = $"INSERT INTO {n} VALUES (?, ?);";

or, if you insist in concatenation:

cmdString = $"INSERT INTO {n}" + " VALUES (?, ?);";
//notice the space here ----------^

also, check if n contains existing table name

Depend on n value, you will have different cmdString. Probably, n contains table name without space, so, resulting sting will have table name and value glued together. Check value of cmdString in debugger (or output it to log).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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