SQL 查询"Data type mismatch in criteria expression."



我正在处理Form,它将大约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();
            }
        }

最新更新