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];
Related
Trying to fill a ComboBox after I insert a value in another TextBox. It keeps returning:
System.Data.SqlClient.SqlException: 'Incorrect syntax near ','.'
public void carrega_status()
{
string sql2 = "select * from tb02_alarme WHERE tb02_desc =" + txtdescala + " ;";
SqlConnection conn1 = Conexao.ObterConexao();
SqlDataAdapter da2 = new SqlDataAdapter(sql2, conn1);
DataTable resultado = new DataTable();
resultado.Clear();
txtstatus.DataSource = null;
da2.Fill(resultado);
txtstatus.DataSource = resultado;
txtstatus.ValueMember = "tb02_class";
txtstatus.DisplayMember = "tb02_class";
txtstatus.SelectedItem = "";
txtstatus.Refresh();
}
The error presents itself on da2.Fill(resultado);.
try this solution that works with me :
string sql2 = "select * from tb02_alarme WHERE tb02_desc ='" + txtdescala + "' ;";
It is never a good idea to leave yourself open to SQL injection. Especially if you are just learning, you should learn the correct way from the start - instead of learning the hard way.
Here is a simple tutorial on how to do this.
People can answer your question all they want, but it won't help you in the long run. With all the comments telling you to use parameters, you should really heed the warning, as all of these people are the experts trying to help you!
I have a OleDbCommand in a Visual Studios c# windows forms project, and I am trying to select the name of every item in my Access Table Stock where the value of a calculated field in that table is less than one. The result type of the calculated field in Access is set to decimal, and the code looks as if it should work, but for whatever reason it doesn't. Could you help me?
Here is my code:
loginForm.connection.Open();
stockLowString = "";
var checkStockLowCommand = new OleDbCommand("SELECT stockName FROM Stock WHERE (stockLowCalculation < '" + Convert.ToDecimal(1) + "')",loginForm.connection);
OleDbDataReader checkStockLowReader = checkStockLowCommand.ExecuteReader();
while (checkStockLowReader.Read())
{
stockLowString = stockLowString + checkStockLowReader.GetString(0) + " ";
}
if (stockLowString != "")
{
MessageBox.Show("There are some Stock Items that are low, these are" + Environment.NewLine + stockLowString);
}
loginForm.connection.Close();
The error occurs on the line
OleDbDataReader checkStockLowReader = checkStockLowCommand.ExecuteReader();
Thanks in advance for your help.
Problem Solved, or at least avoided. I just put the calculation in the Command rather than use a calculated field.
The question is still valid though, as I didn't solve it.
Open the database and check the type of the field "stockLowCalculation" it's most likely not decimal.. I suggest you rework your query and make it parametrized. This way you would evade most of the possible data type mismatch errors.
string conS ="..."; // connection string
var param = 1;
using (var connection = new OleDbConnection(conS))
{
string queryString = "SELECT stockName FROM Stock WHERE stockLowCalculation < #var"
var cmd = new OleDbCommand(queryString, connection);
cmd.Parameters.Add(new OleDbParameter("#var", param));
connection.Open();
OleDbDataAdapter adapt = new OleDbDataAdapter(cmd);
}
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 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 A anb B in String format
A = 14/01/2007
B = 22:10:39
I try to insert date and time:
SQL = "insert into MyTbl(Tdate,Ttime) value ('" + Convert.ToDateTime(A) + "','" + Convert.ToDateTime(B) + "')";
i got ORA-01843 error, what I can do ?
thank's in advance
Don't use raw SQL to insert values. Use a parameterized query instead. Parse your strings into .NET DateTime (or DateTimeOffset) and TimeSpan values in the normal way, and then use something like:
string sql = "insert into MyTbl(Tdate,Ttime) values (:date, :time)";
using (OracleCommand cmd = new OracleCommand(sql, connection))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("date", OracleType.DateTime).Value = date;
cmd.Parameters.Add("time", OracleType.IntervalDayToSecond).Value = time;
cmd.ExecuteNonQuery();
}
(Obviously adjust for the types of your actual fields.)
The error is due to the month, try:
TO_DATE(A, 'DD/MM/YYYY')
Remember that Oracle doesn't have a time-only field.
You're trying to insert a time-only field into a datetime. My guess is that the CLR is turning B into 00/00/00 22:10:39, which isn't a valid oracle date. For example:
SQL> select to_date('00/00/00', 'MM/DD/YY') from dual;
select to_date('00/00/00', 'MM/DD/YY') from dual
*
ERROR at line 1:
ORA-01843: not a valid month
Either way, Convert.ToDateTime(B) probably isn't returning the right thing.
Also, this:
"insert into MyTbl(Tdate,Ttime) value ("
should be this:
"insert into MyTbl(Tdate,Ttime) values ("
...but I'm guessing that's just a typo here.
However i tried Jon method, it didnt work for me for date also time. So i found this method for datetime. Maybe that helps someone in next future too.
OracleParameter oPrm;
oPrm = cmd.CreateParameter();
oPrm.ParameterName = ":myDate";
oPrm.OracleDbType = OracleDbType.Date;
oPrm.Value = DateTime.Now; //for date
cmd.Parameters.Add(oPrm);