Syntax error in query expression

痴心易碎 提交于 2019-12-14 02:32:19

问题


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.



来源:https://stackoverflow.com/questions/21928185/syntax-error-in-query-expression

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!