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();
Related
I have a query to insert a row into a table, which has a field called ID, which is populated using an AUTO_INCREMENT on the column. I need to get this value for the next bit of functionality, but when I run the following, it always returns 0 even though the actual value is not 0:
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', " + bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ")";
int id = Convert.ToInt32(comm.ExecuteScalar());
According to my understanding, this should return the ID column, but it just returns 0 every time. Any ideas?
EDIT:
When I run:
"INSERT INTO INVOICE (INVOICE_DATE, BOOK_FEE, ADMIN_FEE, TOTAL_FEE, CUSTOMER_ID) VALUES ('2009:01:01 10:21:12', 50, 7, 57, 2134);last_insert_id();"
I get:
{"You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'last_insert_id()' at line 1"}
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertStatement; // Set the insert statement
comm.ExecuteNonQuery(); // Execute the command
long id = comm.LastInsertedId; // Get the ID of the inserted item
[Edit: added "select" before references to last_insert_id()]
What about running "select last_insert_id();" after your insert?
MySqlCommand comm = connect.CreateCommand();
comm.CommandText = insertInvoice;
comm.CommandText += "\'" + invoiceDate.ToString("yyyy:MM:dd hh:mm:ss") + "\', "
+ bookFee + ", " + adminFee + ", " + totalFee + ", " + customerID + ");";
+ "select last_insert_id();"
int id = Convert.ToInt32(comm.ExecuteScalar());
Edit: As duffymo mentioned, you really would be well served using parameterized queries like this.
Edit: Until you switch over to a parameterized version, you might find peace with string.Format:
comm.CommandText = string.Format("{0} '{1}', {2}, {3}, {4}, {5}); select last_insert_id();",
insertInvoice, invoiceDate.ToString(...), bookFee, adminFee, totalFee, customerID);
Use LastInsertedId.
View my suggestion with example here: http://livshitz.wordpress.com/2011/10/28/returning-last-inserted-id-in-c-using-mysql-db-provider/
It bothers me to see anybody taking a Date and storing it in a database as a String. Why not have the column type reflect reality?
I'm also surprised to see a SQL query being built up using string concatenation. I'm a Java developer, and I don't know C# at all, but I'd wonder if there wasn't a binding mechanism along the lines of java.sql.PreparedStatement somewhere in the library? It's recommended for guarding against SQL injection attacks. Another benefit is possible performance benefits, because the SQL can be parsed, verified, cached once, and reused.
Actually, the ExecuteScalar method returns the first column of the first row of the DataSet being returned. In your case, you're only doing an Insert, you're not actually querying any data. You need to query the scope_identity() after you're insert (that's the syntax for SQL Server) and then you'll have your answer. See here:
Linkage
EDIT: As Michael Haren pointed out, you mentioned in your tag you're using MySql, use last_insert_id(); instead of scope_identity();
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.
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();
I want to update a table with the time difference between two events. I've implemented this code:
TimeSpan ts = vett[0] - vett[1];
MySqlCommand cmdup = new MySqlCommand();
cmdup.CommandText = "UPDATE event_move SET diff_time=" + ts + "WHERE id_event_move=" + id_move[0];
cmdup.Connection = myConn;
myConn.Open();
cmdup.ExecuteNonQuery();
myConn.Close();
My Visual Studio 2010 indicates a syntax error at the line cmdup.CommandText = ...
Might you help me?
Thanks in advance
The source of the mistake is probably the missing space as Giovanni says.
My tip would be to use String.Format method.
cmdup.CommandText = String.Format("UPDATE event_move SET diff_time={0} WHERE id_event_move={1}", ts, id_move[0]);
Have you used this, you would spot the missing space immediately.
Add space before WHERE condiction:
cmdup.CommandText = "UPDATE event_move SET diff_time=" + ts + " WHERE id_event_move=" + id_move[0];
My current best code is:
string delNonQuery = "DELETE FROM " + Settings.DataSource + " WHERE #keycolumn=#keyuid";
SqlCommand cmd = new SqlCommand(delNonQuery,readerConn);
SqlParameter kc = new SqlParameter("keycolumn", SqlDbType.VarChar);
SqlParameter key = new SqlParameter("keyuid", SqlDbType.VarChar);
cmd.Parameters.Add(kc).Value = Settings.KeyColumn;
cmd.Parameters.Add(key).Value = Page.Request["key"].ToString().Trim();
readerConn.Open();
cmd.ExecuteScalar();
readerConn.Close();
This executes but affects a whopping zero rows. If I change the SqlDbType on keyuid to UniqueIdentifier it just ends up with me getting a dozen variations on "failed to convert character string into uniqueidentifier". I have to use a parameterized query for data cleanliness, I'm just really stuck as to how...
You can't specify a parameter for a column name - you need to concatenate it the same way you do for the table name.
This:
"DELETE FROM " + Settings.DataSource + " WHERE #keycolumn=#keyuid"
Should change to:
"DELETE FROM " + Settings.DataSource + " WHERE " + Settings.KeyColumn + " =#keyuid"
Though I would probably write it as:
string delNonQuery = string.Format("DELETE FROM {0} WHERE {1} = #keyuid",
Settings.DataSource,
Settings.KeyColumn);
For completeness sake, I will mention that this is open to SQL injection. You need to make sure your Settings values are clean.
I don't think you can parameterise the column name ("keycolumn")
Try this:
string delNonQuery = string.Format("DELETE FROM " + Settings.DataSource + " WHERE {0}=#keyuid", Settings.KeyColumn);
SqlCommand cmd = new SqlCommand(delNonQuery,readerConn);
SqlParameter key = new SqlParameter("keyuid", SqlDbType.VarChar);
cmd.Parameters.Add(key).Value = Page.Request["key"].ToString().Trim();
readerConn.Open();
cmd.ExecuteScalar();
readerConn.Close();
Usual warnings apply regarding concatanating strings to build SQL; this is likely a security risk.
The best method might be to encapsulate your SQL in a stored procedure, pass the column name and value as parameters and then execute using dynamic SQL.
You need to convert the string to GUID:
Relevant Lines:
SqlParameter key = new SqlParameter("keyuid", SqlDbType.UniqueIdentifier);
...
cmd.Parameters.Add(key).Value = new Guid(Page.Request["key"].ToString().Trim());
Which only solves the GUID/UniqueIdentifer issue