簡體   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