Syntax error in query expression

2019-08-12 15:31发布

问题:

string q = "UPDATE tableAbsensi SET Absen_keluar =('"+(DateTime.Now.ToString("hh:mm"))+"') WHERE ID ='"+ idkaryawantxt.Text.ToString() + "' AND Tanggal ='" + (DateTime.Now.ToString("MM-dd-yyyy"));

I think I have error in my syntax, can you guys help me? Thanks

here's the picture of error : http://sadpanda.us/images/1889033-X8SIZZN.jpg

回答1:

It looks like you're missing a quote. This:

AND Tanggal ='" + (DateTime.Now.ToString("MM-dd-yyyy"));

should probably be

AND Tanggal ='" + (DateTime.Now.ToString("MM-dd-yyyy") + "');

But you really should use parameters instead to prevent errors like these and also SQL injection.



回答2:

Please don't do that!

You should never use string concatenations in your sql queries. Always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

With this concatenations, you might forget to use some comma, quotes, brackets etc..

Also use the using statement to dispose your Connection and Command. For example;

using(OleDbConnection con = new OleDbConnection(ConnectionString))
using(OleDbCommand cmd = com.CreateCommand())
{
   string s = "UPDATE tableAbsensi SET Absen_keluar=? WHERE ID=? AND Tanggal=?";
   cmd.CommandText = s;
   cmd.Parameters.AddWithValue("@absen", DateTime.Now.ToString("hh:mm"));
   cmd.Parameters.AddWithValue("@id", idkaryawantxt.Text.ToString());   
   cmd.Parameters.AddWithValue("@tanggal",  DateTime.Now.ToString("MM-dd-yyyy")); 
   cmd.ExecuteNonQuery();  
}


回答3:

Don't use string concatenation to insert values into SQL code. Always use parameters and issues like this caused by formatting just go away. To learn why and how to use parameters, check this out.