[英]SQL query “Data type mismatch in criteria expression.”
I'm working on Form that sends about 9 fields to my SQL ACCESS database and i got this error. 我正在处理将大约9个字段发送到我的SQL ACCESS数据库的表单,但出现此错误。 "Data type mismatch in criteria expression."
“条件表达式中的数据类型不匹配。” i'm sure it's something with the ' x ' i put in my query but still can't figure out what is THE problem.
我确定查询中有' x '的问题,但仍然无法弄清问题所在。
it's (int,int,string,string,string,int,int,string,int,int)
format 它是
(int,int,string,string,string,int,int,string,int,int)
格式
string SqlStr = string.Format("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values({0},{1},'{2}','{3}','{4}',{5},{6},'{7}',{8},{9})", s.ClientId,s.OrderId,s.Date,s.CardTyp,s.PayMethod,s.Ex_Y,s.Ex_M,s.CcComp,s.CcNum,s.TotalSale);
Thanks for your help. 谢谢你的帮助。
String.Format will not be a good approach for building queries. String.Format将不是构建查询的好方法。 I suggest you to use, Parameterised queries that helps you to specify the type too and also its more helpful to prevent injection: Here is an example for you:
我建议您使用参数化查询,它也可以帮助您指定类型,并且对防止注入更为有用:这是一个示例:
string query = "insert into Orders" +
"(client_id,order_id,date_,card_typ,...)" +
" values(@client_id,@order_id,@date_,@card_typ...)";
using (SqlCommand sqCmd = new SqlCommand(query, con))
{
con.Open();
sqCmd.Parameters.Add("@client_id", SqlDbType.Int).Value = s.ClientId;
sqCmd.Parameters.Add("@order_id", SqlDbType.VarChar).Value = s.OrderId;
sqCmd.Parameters.Add("@date_", SqlDbType.DateTime).Value = s.Date;
sqCmd.Parameters.Add("@card_typ", SqlDbType.Bit).Value = s.CardTyp;
// add rest of parameters
//Execute the commands here
}
Note: I have included only few columns in the example, you can replace ...
with rest of columns. 注意:在示例中,我只包含了几列,您可以将
...
用其余的列替换。
Please dont use a concatenation string ... 请不要使用连接字符串...
Here is an example : 这是一个例子:
using (SqlConnection connection = new SqlConnection("...connection string ..."))
{
SqlCommand command = new SqlCommand("insert into Orders(client_id,order_id,date_,card_typ,pay_mthd,ex_y,ex_m,cc_comp,cc_num,t_sale)values(@client_id,@order_id,@date_,@card_typ,@pay_mthd,@ex_y,@ex_m,@cc_comp,@cc_num,@t_sale)", connection);
SqlParameter pclient_id = new SqlParameter("@client_id", System.Data.SqlDbType.Int);
pclient_id.Value = 12;
command.Parameters.Add(pclient_id);
SqlParameter pcard_typ = new SqlParameter("@card_typ", System.Data.SqlDbType.VarChar);
pcard_typ.Value = "some value";
command.Parameters.Add(pcard_typ);
try
{
connection.Open();
command.ExecuteNonQuery();
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
finally
{
connection.Close();
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.