繁体   English   中英

SQL查询“条件表达式中的数据类型不匹配。”

[英]SQL query “Data type mismatch in criteria expression.”

我正在处理将大约9个字段发送到我的SQL ACCESS数据库的表单,但出现此错误。 “条件表达式中的数据类型不匹配。” 我确定查询中有' x '的问题,但仍然无法弄清问题所在。

它是(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);

谢谢你的帮助。

String.Format将不是构建查询的好方法。 我建议您使用参数化查询,它也可以帮助您指定类型,并且对防止注入更为有用:这是一个示例:

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
}

注意:在示例中,我只包含了几列,您可以将...用其余的列替换。

请不要使用连接字符串...

这是一个例子:

        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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM