Reputation: 61
I'm working on Form that sends about 9 fields to my SQL ACCESS database and i got this error. "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.
it's (int,int,string,string,string,int,int,string,int,int)
format
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.
Upvotes: 0
Views: 717
Reputation: 715
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();
}
}
Upvotes: 0
Reputation: 29006
String.Format will not be a good approach for building queries. 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.
Upvotes: 2