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).
Related
I'm trying to optimise the code for an insert statement in SQLite.
I have a problem when inserting multiple values into SQLite from C# Application.
If I try this directly into SQL:
INSERT INTO TBL4 (ID,zID,d) VALUES (6144,1,1),(6144,1,2);
the statement writes two rows of data into table name TBL4.
But, if I want to use this statement in c# and execute it, I have some errors getting from database (error is random.)
Here is the code from c#:
//this is just db connection
string connstr = "Data Source = "+frm.basedir+";"+frm.basever+";";
SQLiteConnection conn = new SQLiteConnection(connstr);
conn.Open();
//working code, successful inserted data into SQL
//g and d variable contain values: 6144 and 2
string sql3 = "INSERT INTO tbl3 (id,d) values (" + g + "," + d + ")";
SQLiteCommand comm3 = new SQLiteCommand(sql3, conn);
comm3.ExecuteNonQuery();
//not working code, throws an error
string sql4 = "INSERT INTO tbl4 (ID,zID,d) VALUES (6144,1,1),(6144,1,2)";
SQLiteCommand comm4 = new SQLiteCommand(sql4, conn);
comm4.ExecuteNonQuery();
My SQLitedatabse is 3.8 version.
Thank in advance
SqlConnection cn = new SqlConnection("user id=ID;" +
"password=PASS;server=svr;" +
"Trusted_Connection=no;" +
"database=db; " +
"connection timeout=30");
cn.Open();
SqlCommand command1 = new SqlCommand();
command1.Connection = cn;
Console.WriteLine(ListofOrders.Count);
for (int i = 0; i < ListofOrders.Count; i++)
command1.CommandText += string.Format("update table set Status='Expired' where GUID={0};", ListofOrders[i].ToString());
command1.ExecuteNonQuery();
// LogicHandler.UpdateActiveOrders();
Console.WriteLine("DONE", ConsoleColor.Cyan);
Getting error at this step: command1.ExecuteNonQuery(); Error Message: The multi-part identifier could not be bound.
What i am trying here is I am running a select query and getting that data into the ListofOrders list from that I wanna run the update to those data in the list.
Please help
If you use a Reserved Keyword like table you have to wrap it in square brackets: [table]. But it would be better to not use them in the first place.
I guess you need to wrap the Guid with apostrophes like in GUID='{0}'. Howver, you should use sql-parameters instead of string concatenation, always. That prevents also sql-injection.
string update = #"update tablename -- or [Table] but i wouldnt do that
set Status='Expired'
where GUID=#GUID";
command1.CommandText = update;
command1.Parameters.Add("#GUID", SqlDbType.UniqueIdentifier).Value = new Guid(ListofOrders[i].ToString());
As an aside, why have you used command1.CommandText += instead of just command1.CommandText =? That is at least confusing, if you reuse the command it could also cause errors.
I know how to use Text Box value in Access query for string fields, but i am unable to understand how to use it for int fields.
I am writing the following query and receiving error messages.
ERROR MESSAGE: No value given for one or more required parameters.
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " +textBox2.Text , conn);
conn.Open();
cmd.ExecuteNonQuery();
I also tried to convert textBox2 into int, but its also given me an error message.
Input string was not in a correct format.
int Id= Convert.ToInt16(textBox2.Text);
OleDbCommand cmd = new OleDbCommand("Update Table1 Set Name= '" + textBox2.Text + "' where ID= " + Id , conn);
conn.Open();
cmd.ExecuteNonQuery();
This answer corrects your problem
First, the TextBox for Name is not the same Textbox used for ID
Second, do not concatenate strings to build sql commands. It is very error prone and open to a well know sql vulnerability called Sql Injection
string queryText = Update Table1 Set Name= ? where ID= ?";
OleDbCommand cmd = new OleDbCommand(queryText, conn);
cmd.Parameters.AddWithValue("#p1", TextBox1.Text);
cmd.Parameters.AddWithValue("#p2", Convert.ToInt32(TextBox2.Text));
conn.Open();
cmd.ExecuteNonQuery();
Here I have removed the string concatenation and inserted two parameters placeholders (?),
then I have added to the OleDbCommand two parameters and their values.
When executing the query the OleDb code will replace the placeholders with the actual values checking for invalid characters and invalid sql statements
I try to find a way to protect apostrophie in my query string. I have a value in string format that contain apostrophie and it throw me an error when I tried to insert
ex :
Insert into ["excelApp.worksheetsList.ElementAt(0).Name "$"] " + ([col1], [col2])
values values" + " ('" + val1 + "', '" + val2 + "');")
This is an exemple. here val1 contains "hereIsMy'value".
Thanks for helping me
You should use parametrized queries and you don't have to worry about single quotes in query
using(OleDbConnection cn = new OleDbConnection(GetConnectionString()))
{
cn.Open();
string cmdText = "Insert into [" + excelApp.worksheetsList.ElementAt(0).Name + "$] " +
"([col1], [col2]) values (?, ?)";
OleDbCommand cmd = new OleDbCommand(cmdText, cn)
cmd.Parameters.AddWithValue("#p1", val1);
cmd.Parameters.AddWithValue("#p2", val2);
cmd.ExecuteNonQuery();
}
In this example your command text consist of a single string with placeholders for the parameters value. Then a command object is declared to have that string and two parameters are added at its collection of parameters. They are created according to the variable type passed as value. So, if val1 and val2 are strings and a single quote (apostrophe) is present it is automatically formatted for the insert/delete/update or select operation requested
Use parameterized commands and you won't have to worry about such things. You won't have to worry about apostrophes and a bunch of other problems.
Please help me, I don't know what can be wrong with the following code:
OdbcConnection conn = new OdbcConnection(connString);
String query = "INSERT INTO customer (custId, custName, custPass, "+
"custEmail, custAddress, custAge) VALUES (" +
"#ID, #Name, #Pass, #Email, #Address, #Age)";
OdbcCommand exe = new OdbcCommand(query, conn);
exe.Parameters.Add("#ID", OdbcType.UniqueIdentifier).Value = id;
exe.Parameters.Add("#Name", OdbcType.VarChar).Value = name;
exe.Parameters.Add("#Pass", OdbcType.VarChar).Value = pass;
exe.Parameters.Add("#Email", OdbcType.VarChar).Value = email;
exe.Parameters.Add("#Address", OdbcType.VarChar).Value = address;
exe.Parameters.Add("#Age", OdbcType.Int).Value = age;
conn.Open();
exe.ExecuteNonQuery(); // ERROR [07002] [Microsoft][ODBC Microsoft Access Driver] Too few parameters. Expected 6.
This code throws me Too few parameters. error when I am trying to execute query. The database is fine, it works fine when I hardcode values into a query, instead of using parameters.
Thank you.
From MSDN:
When CommandType is set to Text, the .NET Framework Data Provider for ODBC does not support passing named parameters to an SQL statement or to a stored procedure called by an OdbcCommand. In either of these cases, use the question mark (?) placeholder. For example:
SELECT * FROM Customers WHERE CustomerID = ?
Rewrite your query to
OdbcConnection conn = new OdbcConnection(connString);
String query = "INSERT INTO customer (custId, custName, custPass, "+
"custEmail, custAddress, custAge) VALUES (" +
"?, ?, ?, ?, ?, ?)";
Order of Parameter counts!
EDIT: Parameter can be added this way:
OdbcCommand exe = new OdbcCommand(query, conn);
exe.Parameters.Add("ID", OdbcType.UniqueIdentifier).Value = id;
exe.Parameters.Add("Name", OdbcType.VarChar).Value = name;
exe.Parameters.Add("Pass", OdbcType.VarChar).Value = pass;
exe.Parameters.Add("Email", OdbcType.VarChar).Value = email;
exe.Parameters.Add("Address", OdbcType.VarChar).Value = address;
exe.Parameters.Add("Age", OdbcType.Int).Value = age;
One of your columns in your query does not exist.
Please check your column names.
Typically you'll see this when you misspell a column name in your SQL statement. Are you sure of those column names (custId, custName, etc.)?
try changing pass to passw maybe it is getting mixed up with asp identifier...