im using access database and im getting this weird error...
missing semicolon at the end of sql statement...
p.s i try to put the semicolon but again same thing...error again...
please help.
this is the code and the error start at Insert Into Statement :
oleDbConnection1.Open();
Int32 sasia_aktuale;
Int32 sasia_e_shtuar = Convert.ToInt32(textBox1.Text.Trim());
string kerkesa = "select * from magazina where emri = '"+listBox1.SelectedItem+"'";
OleDbCommand komanda = new OleDbCommand(kerkesa, oleDbConnection1);
OleDbDataReader lexo = komanda.ExecuteReader();
lexo.Read();
sasia_aktuale = Convert.ToInt32(lexo.GetValue(2).ToString());
lexo.Close();
Int32 sasia_totale = sasia_aktuale + sasia_e_shtuar;
oleDbDataAdapter1.InsertCommand.CommandText =
"insert into magazina(sasia) values('" + sasia_totale + "') where emri= '" + listBox1.SelectedItem + "'";
oleDbDataAdapter1.InsertCommand.ExecuteNonQuery();
MessageBox.Show("Sasia per produktin " + listBox1.SelectedItem + " u shtua me sukses!", "Sasia u shtua");
oleDbConnection1.Close();
You are mixing a WHERE clause with an INSERT statement, the two do not go together:
oleDbDataAdapter1.InsertCommand.CommandText =
"insert into magazina(sasia) values('" + sasia_totale + "')";
Do you mean an UPDATE statement?
I'd also advise you to look up SQL injecton, and using SqlParameters to build your queries. Your code, currently is very insecure.
I can see you are after an UPDATE command. The INSERT SQL command is just going to insert whatever you give it. An example of an UPDATE command, using SqlParameters to help avoid SQL injection, is below, although this is untested as I obviously don't have access to your setup (nor am I doing this with an IDE):
var updateCommand = new OleDbCommand("UPDATE magazina SET sasia = #sasia_totale WHERE emri = #emri");
updateCommand.Parameters.AddWithValue("#sasia_totale", sasia_totale);
updateCommand.Parameters.AddWithValue("#emri", listBox1.SelectedItem.ToString());
oleDbDataAdapter1.UpdateCommand = updateCommand;
oleDbDataAdapter1.UpdateCommand.ExecuteNonQuery();
Related
I'm using a a multiple query with insert and update statement together.
The problem is that if query will not be completed(for some reason e.x bad internet connection) my SQL Server table keeps rubbish.
Example of query:
SqlCommand cmd = new SqlCommand("INSERT INTO CustomerTrans (TableName, UserID, UserName, SumQuantity, SumPrice, SumRealPrice, SumExtrasPrice, SumTotal, SumDiscountTotal, DateTime) SELECT " + Connection.TableName + ",' " + Connection.UserID + "', '" + Connection.Username + "',Sum(Quantity),Sum(Price),Sum(RealPrice),Sum(ExtrasPrice), Sum(Quantity * Price),Sum(Quantity * DiscountPrice),'" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "' from InventoryTransTemp where active=1 and TableName=" + Connection.TableName + ";update InventorytransTemp set TrnDocumentID=(select max(TrnDocumentID) from CustomerTrans where UserID='" + Connection.UserID + "'),Active=0 where TableName=" + Connection.TableName + " and Active=1", con);
cmd.ExecuteNonQuery();
Take a photo from a query which has not be completed properly look query 2989 it has NULL values. I want to avoid inserting something if query is not be completed properly.
Sorry for my previous Question it was Unclear
Try it like this:
string sql =
"INSERT INTO CustomerTrans" +
" (TableName, UserID, UserName, SumQuantity, SumPrice, SumRealPrice, SumExtrasPrice, SumTotal, SumDiscountTotal, DateTime)" +
" SELECT #TableName, #UserID, #Username, Sum(Quantity), Sum(Price), Sum(RealPrice), Sum(ExtrasPrice), Sum(Quantity * Price), Sum(Quantity * DiscountPrice), current_timestamp" +
" FROM InventoryTransTemp" +
" WHERE active=1 and TableName= #TableName;\n" +
"SELECT #TranID = scope_identity;\n"
"UPDATE InventorytransTemp" +
" SET TrnDocumentID=#TranID ,Active=0" +
" WHERE TableName= #Tablename and Active=1;";
using (var con = new SqlConnection("connection string here"))
using (var cmd = new SqlCommand(sql, con))
{
//I'm guessing at exact column types/lengths here.
// You should update this to use your exact column types and lengths.
// Don't let ADO.Net try to guess this for you.
cmd.Parameters.Add("#TableName", SqlDbType.NVarChar, 20).Value = Connection.TableName;
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = Connection.UserID;
cmd.Parameters.Add("#Username", SqlDbType.NVarChar, 20).Value = Connection.Username;
cmd.Parameters.Add("#TranID", SqlDbType.Int).Value = 0; //placeholder only
con.Open();
cmd.ExecuteNonQuery();
}
Note the improved formatting of the query, the use of scope_identity() to get the new identity value rather than a nested select statement that might not be atomic, that I avoided ALL uses of string concatenation to substitute data into the query, that I avoided the AddWithValue() method entirely in favor of an option that doesn't try to guess at your parameter types, and the use of using blocks to be sure the SqlClient objects are disposed properly.
The only thing I'm still concerned about is if your INSERT/SELECT operation might create more than one new record. In that case, you'll need to handle this a different way that probably involves explicit BEGIN TRANSACTION/COMMIT statements, because this code only gets one #TranID value. But in that case, the original code was broken, too.
string query = "update library_database.members set name='" + txtname.Text + "', Adresss='" + richtxtadress.Text + "',";
query = query + "Status='" + cmbstatus.SelectedText + "',Type='" + cmbtype.SelectedText + "',";
query = query + "Date_expiry='" + dateofexpiry.Value.ToString("yyyy-MM-dd") + "',#IMG";
query=query+"' where id='";
query = query + txtid.Text + "'";
cmd = new MySqlCommand(query, con);
cmd.Parameters.Add(new MySqlParameter("#IMG", imgbt));
The exception occur SQL Santax error at line 1 near #IMG. Please help how can I solve it?
Looks like you forget to column name when you update your #IMG value.
It should be something like;
query = ... "ColumnName = #IMG" + ...
But please
ALWAYS use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Next time, when you get this kind of sql syntax error, first thing you should try is to run your query in your database manager. Then you can easily see what is wrong with your query and how you can fix it.
I check my SQL Statement many times and it seems that my SQL Statement is Error. I don't why it doesn't work. My SQL Statement is correct and It resulted to this OleDBException "Syntax error in UPDATE statement.".
Here is the code
OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString);
CN.Open();
cmd1 = new OleDbCommand("Update Mosque Set Name='" + txtNAME.Text + "', No='" + Convert.ToInt32(txtNO.Text) + "', place='" + txtPlace.Text + "', group='" + txtGroup.Text + "', description='" + txtdec.Text + "' where id='" + txtID.Text + "'", CN);
cmd1.ExecuteNonQuery();
CN.Close();
need help please to know what is the error here
I don't know what database are you using, but I am sure that GROUP is a reserved keyword in practically any existant SQL database. This word cannot be used without some kind of delimiter around it. The exact kind of delimiter depend on the database kind. What database are you using?
Said that, please do not use string concatenation to build sql commands, but use always a parameterized query. This will allow you to remove any possibilities of Sql Injection and avoid any syntax error if one or more of your input string contains a single quote somewhere
So, supposing you are using a MS Access Database (In Access also the word NO is a reserved keyword and the delimiters for reserved keywords are the square brakets) you could write something like this
string commandText = "Update Mosque Set Name=?, [No]=?, place=?, " +
"[Group]=?, description=? where id=?"
using(OleDbConnection CN = new OleDbConnection(mysql.CON.ConnectionString))
using(OleDbCommand cmd1 = new OleDbCommand(commandText, CN))
{
CN.Open();
cmd1.Parameters.AddWithValue("#p1",txtNAME.Text);
cmd1.Parameters.AddWithValue("#p2",Convert.ToInt32(txtNO.Text));
cmd1.Parameters.AddWithValue("#p3",txtPlace.Text);
cmd1.Parameters.AddWithValue("#p4",txtGroup.Text);
cmd1.Parameters.AddWithValue("#p5",txtdec.Text);
cmd1.Parameters.AddWithValue("#p6",txtID.Text);
cmd1.ExecuteNonQuery();
}
Instead for MySQL you have to use the backticks around the GROUP keyword
string commandText = "Update Mosque Set Name=?, No=?, place=?, " +
"`Group`=?, description=? where id=?"
Hard to tell without knowing the values of the texboxes, but I suspect that one of them has an apostrophe which is causing an invalid syntax.
I recommend using parameters instead:
cmd1 = new OleDbCommand("Update Mosque Set [Name]=#Name, [No]=#No, [place]=#Place, [group]=#Group, [description]=#Description WHERE id=#ID", CN);
cmd1.Parameters.AddWithValue("#Name",txtNAME.Text);
cmd1.Parameters.AddWithValue("#No",Convert.ToInt32(txtNO.Text));
// etc.
I am unable to update my database. I have a table called Table2 and I have in it 3 columns: time, strike and vol. Please check the comments made in the line statements. thanks in advance for the help.
VolLoc = Math.Sqrt(Math.Abs(VarianceLoc));
Console.WriteLine("Local Volatility at strike " + strike1_run + " and time " + time0_run + " is: " + VolLoc + "\n"); // works perfectly at this point, I have a new value for my variable VolLoc
string StrCmd1 = "UPDATE Table2 SET (vol = #vol_value) WHERE ((time = #T0_value) AND (strike = #K1_value))"; // HERE is the problem, when I debug, the cursor steps on it normally but the database is not updated !!
OleDbCommand Cmd1 = new OleDbCommand(StrCmd1, MyConn);
Cmd1.Parameters.Add("#vol_value", OleDbType.VarChar);
Cmd1.Parameters["#vol_value"].Value = VolLoc.ToString();
Cmd1.Parameters.Add("#T0_value", OleDbType.VarChar);
Cmd1.Parameters["#T0_value"].Value = time0_run.ToString();
Cmd1.Parameters.Add("#K1_value", OleDbType.VarChar);
Cmd1.Parameters["#K1_value"].Value = strike1_run.ToString(); //the cursor steps on each of the line statements above, but the database is still not updated
Apart from the missing call to ExecuteNonQuery as stated by other, your code has another error that will show itself when your code will reach the ExecuteNonQuery method.
The word TIME is a reserved keyword in MS-Access Jet SQL.
You need to encapsulate it with square brackets [time]
So, summarizing
string StrCmd1 = "UPDATE Table2 SET vol = #vol_value WHERE " +
"([time] = #T0_value AND strike = #K1_value)";
OleDbCommand Cmd1 = new OleDbCommand(StrCmd1, MyConn);
.......
cmd1.ExecuteNonQuery();
Also, all the parameters are passed as string values. Are you sure that the corresponding fields are of the same datatype (text)
You need to call an Execute method on your OleDbCommand object.
try adding
Cmd1.ExecuteNonQuery();
I have the following code block
SQLiteConnection cnn = new SQLiteConnection("Data Source=" + getDBPath());
cnn.Open();
SQLiteCommand mycommand = new SQLiteCommand(cnn);
string values = "'" + this.section + "','" + this.exception + "','" + this.dateTimeString + "'";
string sql = #"INSERT INTO Emails_Pending (Section,Message,Date_Time) values (" + values + ")";
mycommand.CommandText = sql;
mycommand.ExecuteNonQuery();
cnn.Close();
When I execute it , nothing happens, no errors are produced, but nothing gets inserted, what am I doing wrong?
Path to DB is correct!
Insert statement works, tried it in a SQLLite GUI (no problems there)
Here is the SQL Snippet:
"INSERT INTO Emails_Pending (Section,Message,Date_Time) values ('Downloading Received Messages','Object reference not set to an instance of an object.','04.12.2009 11:09:49');"
How about adding Commit before Close
mycommand.Transaction.Commit();
You should always use transactions and parameterized statements when using sqlite, else the performance will be very slow.
Read here: Improve INSERT-per-second performance of SQLite?
Your approach is vulnerable to sql injection too. A message in an email can have a piece of sql in its body and your code will execute this piece of sql. You can also run into problems when the message in your string values contains a " or a ' .