Ko Su
Ko Su

Reputation: 1

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 };";

Upvotes: 0

Views: 1119

Answers (2)

Nino
Nino

Reputation: 7095

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

Upvotes: 1

Anton Pavlov
Anton Pavlov

Reputation: 216

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).

Upvotes: 0

Related Questions