Insert, Delete or Update cannot be performed? - c#

My query seems to be correct but why is this happening?
OleDbConnection con = new OleDbConnection();
con.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Sparrow vivek\Documents\Billing.accdb";
con.Open();
DateTime a = Convert.ToDateTime(label2.Text);
String query = "INSERT INTO balancesheet (BillNumber,CusName,Date,Amount) values (?,?,?,?)";
OleDbCommand cmd = new OleDbCommand(query, con);
cmd.Parameters.AddWithValue("?",label3.Text);
cmd.Parameters.AddWithValue("?", label4.Text);
cmd.Parameters.AddWithValue("?", a.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("?", label6.Text);
cmd.ExecuteNonQuery();
con.Close();

Your query contains a reserved keyword: Date. To use it you need to use square brackets around that name
String query = "INSERT INTO balancesheet (BillNumber,CusName,[Date],Amount) values (?,?,?,?)";
It is highly recommended to avoid these names. If it is still possible change that name ASAP.
Now let's examine that list of AddWithValue. In this method the datatype of the parameter is automatically determined by the value that you pass. You have every value passed to the parameter collection of type string. But it is probable that your database fields doesn't want a string as value. For example Date,Amount seems requires a datetime and a number
cmd.Parameters.AddWithValue("?",label3.Text);
cmd.Parameters.AddWithValue("?", label4.Text);
cmd.Parameters.AddWithValue("?", a);
cmd.Parameters.AddWithValue("?", Convert.ToDecimal(label6.Text));

Related

Is it possible to insert a value using an apostrophe using this command? Microsoft Access

New to C#. Trying to insert values into a Microsoft Access Database using this code:
string value = "It's a nice day"
con.Open();
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 values('"+ value + "')";
cmd.ExecuteNonQuery();
con.Close();
But I get the error 'Syntax error (missing operator) in query expression' which I'm going to assume, stems from the apostrophe in the string value. Is there any way around this?
Every time you need to pass values to execute an sql query you should ALWAYS use a parameterized query. As you have experienced, apostrophes mess with the syntax when you concatenate strings.
A parameterized query for your case should be
string value = "It's a nice day"
OleDbCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Table1 values(#value)";
cmd.Parameters.Add("#value", OleDbType.VarWChar).Value = value;
cmd.ExecuteNonQuery();
This will remove the problem with apostrophes, interpretation of the decimal point symbol, date format, but, most important even is not easy to exploit with Access, the Sql Injection ack.

Adding to database using Oledb Syntax error in INSERT INTO statement

when i hit the add button to insert a new book, i get an error at cmd.ExecuteNonQuery(); Syntax error in INSERT INTO statement. Am i missing anything?
protected void btnAddBook_Click(object sender, EventArgs e)
{
string connect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|Bookdb.accdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
OleDbCommand cmd = new OleDbCommand("INSERT INTO Books (Title, Author, Price, Edition) VALUES (#Title, #Author, #Price, #Edition)");
cmd.CommandType = CommandType.Text;
cmd.Connection = conn;
cmd.Parameters.AddWithValue("#Title", TextBox1.Text);
cmd.Parameters.AddWithValue("#Author", TextBox2.Text);
cmd.Parameters.AddWithValue("#Price", TextBox3.Text);
cmd.Parameters.AddWithValue("#Edition", TextBox4.Text);
conn.Open();
cmd.ExecuteNonQuery();
conn.Close();
}
The only reason that I can find as a possible failure for your code is if the Price field is a numeric field in your database table. You are creating a parameter with AddWithValue and this method creates a parameter whose datatype is derived from the datatype of the value passed. You pass a string (TextBox3.Text) and so AddWithValue creates a string parameter.
You could try to force the AddWithValue to create a numeric parameter with
cmd.Parameters.AddWithValue("#Price", Convert.ToDecimal(TextBox3.Text));
(Of course assuming a decimal Price column)
Right before you call conn.Open(), you need to call cmd.Prepare(), so that all the parameters you set are actually loaded into the SQL statement.

OleDbDataAdapter Update To dbf [Free Table] -Syntax Error()

When I insert through the OleDbCommand with direct values no problem, it's working fine
OleDbCommand OleCmd1 = new OleDbCommand("Insert into My_Diary (sl_no,reminder) values("+a1+",'CHECK VALUE')", OleCon1);
OleCmd1->ExecuteNonQuery();
But when I like to update through parameter its showing "Syntax Error"....I can't identify my mistake...
string MyConStr = "Provider=VFPOLEDB.1; Data Source='C:\\For_Dbf'; Persist Security Info=False";
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (#sl_no,#reminder) ";
VFPDAp=gcnew OleDbDataAdapter();
VFPDApMy_Table1InsertCommand = gcnew OleDbCommand(InsSavDiaryCmd, OleCon1);
WithInsVar = VFPDAp.InsertCommand.Parameters;
WithInsVar.Add("#sl_no", OleDbType.Integer, 10, "sl_no");
WithInsVar.Add("#reminder", OleDbType.Char, 250, "reminder");
OleCon1.ConnectionString = MyConStr;
OleCon1.Open();
OleDbTransaction Trans=OleCon1.BeginTransaction();
//VFPDAp.DeleteCommand.Transaction = Trans;
//VFPDAp.UpdateCommand.Transaction = Trans;
VFPDAp.InsertCommand.Transaction = Trans;
VFPDAp.Update(MyDataTbl);
Trans.Commit();
OleCon1.Close();
The OleDbCommand doesn't use named parameters. You need to change the insert statement so that it uses questions.
InsSavDiaryCmd = "Insert into My_Table1 (sl_no,reminder) values (?, ?) ";
You need to make sure that you have a parameter for each question mark and make sure that the parameters are inserted in order of their use in the insert statement.
** If you'd like to use name parameters... you can try using VfpClient which is a project that I'm working on to make data access a little nicer from .Net.

How to insert a record into a access table using oledb?

I have a this Items table in ms access
Items(Table)
Item_Id(autonumber)
Item_Name(text)
Item_Price(currency)
and i'm trying to insert a record using this code.
OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString());
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values ('" + itemNameTBox.Text + "','" + Convert.ToDouble(itemPriceTBox.Text) + "')";
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
myCon.Close();
Code is running without error but at the end no record is found in the table what mistake i'm doing?
Your sql insert text doesn't use parameters.
This is the cause of bugs and worse (SqlInjection)
Change your code in this way;
using(OleDbConnection myCon = new OleDbConnection(ConfigurationManager.ConnectionStrings["DbConn"].ToString()))
{
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "insert into Items ([Item_Name],[Item_Price]) values (?,?)";
cmd.Parameters.AddWithValue("#item", itemNameTBox.Text);
cmd.Parameters.AddWithValue("#price", Convert.ToDouble(itemPriceTBox.Text));
cmd.Connection = myCon;
myCon.Open();
cmd.ExecuteNonQuery();
System.Windows.Forms.MessageBox.Show("An Item has been successfully added", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
Of course this assumes that the text box for price contains a correct numeric value.
To be sure add this line before calling the code above
double price;
if(double.TryParse(itemPriceTBox.Text, out price) == false)
{
MessageBox.Show("Invalid price");
return;
}
then use price as value for the parameter #price
**EDIT 4 YEARS LATER **
This answer needs an update. In the code above I use AddWithValue to add a parameter to the Parameters collection. It works but every reader should be advised that AddWithValue has some drawbacks. In particular if you fall for the easy path to add just strings when the destination column expects decimal values or dates. In this context if I had written just
cmd.Parameters.AddWithValue("#price", itemPriceTBox.Text);
the result could be a syntax error or some kind of weird conversion of the value and the same could happen with dates. AddWithValue creates a string Parameter and the database engine should convert the value to the expected column type. But differences in locale between the client and the server could create any kind of misinterpretation of the value.
I think that it is always better to use
cmd.Parameters.Add("#price", OleDbType.Decimal).Value =
Convert.ToDecimal(itemPriceTBox.Text);
More info on AddWithValue problems can be found here

Insert query for ms-access with Oledb object getting exception of not a valid query

I'm using the following code and it is giving the invalid Insert command exception.
row the DataRow object to be added to the database , conn is the OleDBConnection object.
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = `"Insert Into Appointments(ID,Body,End,Location,Start,Subject,Properties)"
+ "Values(#ID,#Body,#End,#Location,#Start,#Subject,#Properties)";
cmd.Parameters.Add("#ID", OleDbType.WChar).Value = row[0].ToString();
cmd.Parameters.Add("#Body", OleDbType.WChar).Value = row[1].ToString();
cmd.Parameters.Add("#End", OleDbType.Date).Value = Convert.ToDateTime(row[2]).Date.ToLongDateString();
cmd.Parameters.Add("#Location", OleDbType.WChar).Value = row[3].ToString();
cmd.Parameters.Add("#Start", OleDbType.Date).Value = Convert.ToDateTime(row[4]).Date.ToLongDateString();
cmd.Parameters.Add("#Subject", OleDbType.WChar).Value = row[5].ToString();
cmd.Parameters.Add("#Properties", OleDbType.WChar).Value = row[6].ToString();
conn.Open();
cmd.ExecuteNonQuery(); //At this line exception is generating
conn.Close();
Please help me in this.
You've got one (possibly more) reserved word in your table's field names.
The field name End ... at the very least.
Try
cmd.CommandText = `"Insert Into Appointments(ID,Body,[End],Location,Start,Subject,Properties)"
+ "Values(#ID,#Body,#End,#Location,#Start,#Subject,#Properties)";
Does "Appointments" table support inserting ID? If ID column is the identity value, that may cause problem.
I think that the data-types that you use for your parameters are incorrect.
If your ID column is a numeric column, you shouldn't use OleDbType.WChar, but OleDbType.Integer, for instance
For alfanumeric-columns, I wouldn't use OleDbType.WChar either, but OleDbtype.VarChar.
See the OleDbType enumeration as well.

Categories