I keep getting a 'data type mismatch in criteria expression' when trying to insert into my Access 2010 table. The table has field names of:
GradeKey - AutoNumber,
Grade - Text,
Comments - Text,
TellerNum - Number,
TestName - Text.
The TestName is also a foreign key from another table. Any ideas on what I need to use to fix the data type mismatch?
using (OleDbConnection con = new OleDbConnection(constring))
{
try
{
string cmdstring = "INSERT INTO GRADE (Grade, Comments, TellerNum, TestName) VALUES (#grade, #comments, #teller, #test)";
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.AddWithValue("#teller", OleDbType.Integer).Value = comboBox5.Text;
cmd.Parameters.AddWithValue("#grade", OleDbType.Char).Value = textBox7.Text;
cmd.Parameters.AddWithValue("#comments", OleDbType.Char).Value = textBox10.Text;
cmd.Parameters.AddWithValue("#test", OleDbType.Char).Value = comboBox16.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Submitted Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
}
OleDbType.Integer should be an integer.Try parsing comboBox5.Text to int:
cmd.Parameters.AddWithValue("#teller", OleDbType.Integer).Value = int.Parse(comboBox5.Text);
OleDb does not support named parameters. It only supports positional parameters. You need to add your parameters in the same order as they appear in the query:
cmd.Parameters.AddWithValue("#grade", OleDbType.Char).Value = textBox7.Text;
cmd.Parameters.AddWithValue("#comments", OleDbType.Char).Value = textBox10.Text;
cmd.Parameters.AddWithValue("#teller", OleDbType.Integer).Value = comboBox5.Text;
cmd.Parameters.AddWithValue("#test", OleDbType.Char).Value = comboBox16.Text;
Related
I have tried the code below when I am going to click Save button I got the error of "fatal error encountered during command execution" I rechecked more than two times but unfortunately error not go away. please, anyone kindly fix this error.
private void button1_Click(object sender, EventArgs e)
{
string cid, lname, fname,street,city,state,phone,date,email,aco,actype,des,bal;
cid = label14.Text;
lname = textBox1.Text;
fname = textBox2.Text;
street = textBox3.Text;
city = textBox4.Text;
state = textBox5.Text;
phone = textBox6.Text;
date = dateTimePicker1.Text;
email = textBox8.Text;
aco = textBox7.Text;
actype = comboBox1.Text;
des = textBox10.Text;
bal = textBox11.Text;
con.Open();
MySqlCommand cmd = con.CreateCommand();
MySqlTransaction transaction;
transaction = con.BeginTransaction();
StringBuilder cmdText = new StringBuilder();
cmdText.AppendLine("INSERT into customer (custid,lastname,firstname,street,city,state,phone,date,email) VALUES (#custid,#lastname,#firstname,#street,#city,#state,#phone,#date,#email)");
cmdText.AppendLine("INSERT into account(accid,custid,acctype,description,balance) VALUES (#accid,#custoid,#acctype,#description,#balance)");
cmd.CommandText = cmdText.ToString();
cmd.Connection = con;
cmd.Transaction = transaction;
cmd.Parameters.AddWithValue("#custid", cid);
cmd.Parameters.AddWithValue("#lastname", lname);
cmd.Parameters.AddWithValue("#firstname", fname);
cmd.Parameters.AddWithValue("#street", street);
cmd.Parameters.AddWithValue("#city", city);
cmd.Parameters.AddWithValue("#state", state);
cmd.Parameters.AddWithValue("#phone", phone);
cmd.Parameters.AddWithValue("#date", date);
cmd.Parameters.AddWithValue("#email", email);
cmd.Parameters.AddWithValue("#accid", aco);
cmd.Parameters.AddWithValue("#cusotid", cid);
cmd.Parameters.AddWithValue("#acctype", actype);
cmd.Parameters.AddWithValue("#description", des);
cmd.Parameters.AddWithValue("#balance", bal);
try
{
cmd.ExecuteNonQuery();
transaction.Commit();
MessageBox.Show("Transaction Suceess");
}
catch (Exception ex)
{
transaction.Rollback();
MessageBox.Show(ex.Message);
}
finally
{
con.Close();
}
}
I have seen many developers encountering errors with their SQL because they are using AddWithValue on their SqlCommand. The issue with this is that the command doesn't know the data type of your sql command parameter.
You should use SqlParameterCollection.Add Method (String, SqlDbType, Int32) to specify the data type of the parameter. Refer to SqlDbType Enumeration for the SqlDbType enumeration.
Usage:
cmd.Parameters.Add("#custid", SqlDbType.Int).Value = cid;
cmd.Parameters.Add("#lastname", SqlDbType.Text).Value = lname;
P.S. I am assuming that there are no issues with your SQL connection string.
I'm trying to connect to database file "crepeDB.accdb"
When I added it through data connection, and works fine when I drag any table to appear as data grid in any form but when I try to connect to the database to insert data it gives me this error:
An unhandled exception of type 'System.NotImplementedException' occurred in Additional information: The method or operation is not implemented.
The code I'm using is as follows:
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;");
conn.Open();
string query = "insert into Sales (Sdate,SQuantity) values ('" + dateTimePicker1.Value + "','" + textBox9.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.ExecuteNonQuery();
This is the last thing I need to do in my project, would really appreciate any help.
Do not pass values for your fields concatenating them to form your command, instead use parameters.
int quantity;
if(!Int32.TryParse(textBox9.Text, out quantity))
MessageBox.Show("Invalid number");
else
{
using(OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"insert into Sales (Sdate,SQuantity)
values (#date, #qta)";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("#date", OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#qta", OleDbType.Integer).Value = quantity;
cmd.ExecuteNonQuery();
}
}
This is better because you don't ask someone else to convert your values from a string to the correct datatype. This automatic conversion (in particular with dates) is well know to cause problems when there is some kind of mismatch between the passed string and how the database engine interprets this string
N.B I am assuming the Sdate is a field of type DateTime and SQuantity is a field of type Integer in MS-Access. If not then you can change the OleDbType Int32.TryParse to the correct matching type
It is basically like this . . .
con.Open();
SqlCommand cmd = new SqlCommand(#"insert into tbl_insert values(#name,#email,#add)", con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#add", txtadd.Text);
cmd.ExecuteNonQuery();
con.Close();
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.
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.
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();
}
}
I am having trouble updating data into a table from my C# form. Could someone tell me what I am doing wrong. It does not give me an error and says that it has been submitted successfully. My database show no change however.
try
{
string cmdstring = "UPDATE Test SET COLLECTION_DATE = '#date', SPECIMANID = '#spec', TEST_RESULT = '#result', SUBSTANCE_RESULT = '#substance' WHERE PEOPLESOFT_EMPL_ID = #empID ;";
using (OleDbCommand cmd = new OleDbCommand(cmdstring, con))
{
cmd.Parameters.Add("#date", OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#spec", OleDbType.Char).Value = textBoxSpec.Text;
cmd.Parameters.Add("#result", OleDbType.Char).Value = comboBoxResult.Text;
cmd.Parameters.Add("#substance", OleDbType.Char).Value = comboBoxSubstance.Text;
cmd.Parameters.Add("#empID", OleDbType.Char).Value = textBoxID.Text;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
MessageBox.Show("Submitted Successfully");
}
}
catch (Exception ex)
{
MessageBox.Show("Failed due to " + ex.Message);
}
Problem : You are enclosing the Parameters in your update query within single quotes.
Solution : while using parameterised queries you should not enclose the parameters within single quotes, so you need to remove the single quotes around the parameters in update query.
Try This:
string cmdstring = "UPDATE Test SET COLLECTION_DATE = #date, SPECIMANID = #spec,
TEST_RESULT = #result, SUBSTANCE_RESULT = #substance WHERE PEOPLESOFT_EMPL_ID =
#empID ;";
Suggestion: You are displaying the success mesaage without checking the query execution status.
i would suggest you to verify the ExecuteNonQuery() return value before displaying the Success message.
From MSDN :ExecuteNonQuey()
Executes a Transact-SQL statement against the connection and returns
the number of rows affected.
Try This:
int rowsUpdated = cmd.ExecuteNonQuery();
if(rowsUpdated > 0)
MessageBox.Show("Records Inserted Successfully!");
else
MessageBox.Show("Insertion Failed!");
I am facing error in following Query.According to my knowledge I have written everything perfectly fine. But its giving error that:
"there is an error in update query"
string insert_query = "update aho set read=?,pick=? where Cont_no='" + contract_no + "'";
OleDbCommand ocmd = new OleDbCommand();
ocmd.CommandText = insert_query;
//ocmd.Parameters.AddWithValue("#contrct_no", contract.Text.ToString());
ocmd.Parameters.AddWithValue("#read_val", Convert.ToInt32(read.Text));
ocmd.Parameters.AddWithValue("#pic_val", Convert.ToInt32(pick.Text));
ocmd.Connection = conn;
ocmd.ExecuteNonQuery();
You didn't gave us too much information but..
I think your Cont_no type is some numerical type, not one of the character type. Looks like that's why you get error when you try to add it with ''.
For example like;
Cont_no = '123'
Try this one;
string insert_query = "update aho set [read]=?,pick=? where Cont_no=?";
OleDbCommand ocmd = new OleDbCommand();
ocmd.CommandText = insert_query;
ocmd.Parameters.AddWithValue("#read_val", Convert.ToInt32(read.Text));
ocmd.Parameters.AddWithValue("#pic_val", Convert.ToInt32(pick.Text));
ocmd.Parameters.AddWithValue("#contrct_no", contract_no);
ocmd.Connection = conn;
ocmd.ExecuteNonQuery();
EDIT: HansUp is totally right. Read is a reserved keyword. You should use it with square brackets like [Read] in your query.
In your query string you consider parameters by priority, but when you create them you are giving them a name.
According to http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbcommand.parameters.aspx, OleDbCommand does not support named parameters.
Look at this example (source: http://www.java2s.com/Code/CSharp/Database-ADO.net/PassparametertoOleDbCommand.htm):
using System;
using System.Data;
using System.Data.OleDb;
public class Prepare {
public static void Main () {
String connect = "Provider=Microsoft.JET.OLEDB.4.0;data source=.\\Employee.mdb";
OleDbConnection con = new OleDbConnection(connect);
con.Open();
Console.WriteLine("Made the connection to the database");
OleDbCommand cmd1 = con.CreateCommand();
cmd1.CommandText = "SELECT ID FROM Employee "
+ "WHERE id BETWEEN ? AND ?";
OleDbParameter p1 = new OleDbParameter();
OleDbParameter p2 = new OleDbParameter();
cmd1.Parameters.Add(p1);
cmd1.Parameters.Add(p2);
p1.Value = "01";
p2.Value = "03";
OleDbDataReader reader = cmd1.ExecuteReader();
while(reader.Read())
Console.WriteLine("{0}", reader.GetInt32(0));
reader.Close();
con.Close();
}
}