OleDbException was unhandled: Syntax Error (missing operator) In Query Expression - c#

I am new in creating an application using Visual Stuido 2010 C# and Microsft Access 2007. I am planning to create an application where the user can add data to the database(MS-Access). But I got an error stating that "Syntax Error (missing operator) In Query Expression". I really can't find what's the problem with my code.
This is my code in adding data to the database:
private void buttonSaveFuelLimit_Click(object sender, EventArgs e)
{
string MyConString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\KKKKK\Documents\Visual Studio 2010\Projects\Trial\Trial\gxi.accdb";
OleDbConnection connection = new OleDbConnection(MyConString);
OleDbCommand command = connection.CreateCommand();
command.Connection = connection;
using (OleDbConnection conn = new OleDbConnection(MyConString))
{
connection.Open();
using (OleDbCommand com = connection.CreateCommand())
{
command.CommandText = "insert into fuel_limit(fuel_limit_code, fuel_limit_description) values(?fuel_limit_code, ?fuel_limit_description)";
command.Parameters.Add(new OleDbParameter("?fuel_limit_code", OleDbType.VarChar));
command.Parameters.Add(new OleDbParameter("?fuel_limit_description", OleDbType.VarChar));
command.Parameters["?fuel_limit_code"].Value = textBoxFuelLimitCode.Text;
command.Parameters["?fuel_limit_description"].Value = textBoxFuelLimitDesc.Text;
command.ExecuteNonQuery();
MessageBox.Show("Data Saved");
}
}
}
This is the screen shot of the error message:

You need the values part of the insert into statement.
insert into fuel_limit (fuel_limit_code, fuel_limit_description) values (?fuel_limit_code, ?fuel_limit_description)
Also, it looks like your you need to use the description parameter when setting the value in the line right above the ExecuteNonQuery statment.

--- Edited answer ---
following will work
command.CommandText = "insert into fuel_limit(fuel_limit_code, fuel_limit_description) values(?, ?)";
command.Parameters.AddWithValue(new OleDbParameter("#fuel_limit_code",textBoxFuelLimitCode.Text));
command.Parameters.AddWithValue(new OleDbParameter("#fuel_limit_desc", textBoxFuelLimitDesc.Text));
command.ExecuteNonQuery();
--- old answer ---
here is the line that needs correction
command.CommandText = "insert into fuel_limit(fuel_limit_code, fuel_limit_description)";
//should ne
command.CommandText = "insert into fuel_limit(fuel_limit_code, fuel_limit_description) values(?,?)";

Related

How to Insert data into a MSSQL table using C#

I'm trying to using INSERT to write some data to a MSSQL Database table. I believe my SQL string is correct but I'm getting an error message when I run command.ExecuteScaler(); I've attached the error message in a screen shot. It states I'm using incorrect syntax but I'm not getting any compiler errors.
I'm assuming I'm just doing something wrong.
CODE:
using (SqlConnection connection = new SqlConnection(SQLHelper.CnnCal("CQDB")))
{
connection.Open();
String insert = #"INSERT INTO Skills(SkillName, SkillNumber, SkillLastUpdated, SkillServer) VALUES(" + skills.SkillName + "," + skills.SkillNumber + "," + skills.LastUpdated + "," + skills.CallServer +")";
SqlCommand command = new SqlCommand(insert, connection);
command.ExecuteScalar();
connection.Close();
}
Error Message from exception pop up
Question:
What is the proper way of inserting data into a MSSQL database table?
You should be using Parameters to prevent SQL Injection.
The below code takes care of that:
var query = "INSERT INTO Skills(SkillName, SkillNumber, SkillLastUpdated, SkillServer)
VALUES (#SkillName, #SkillNumber, #SkillLastUpdated, #SkillServer)";
using (SqlConnection connection = new SqlConnection(SQLHelper.CnnCal("CQDB")))
{
using(SqlCommand cmd = new SqlCommand(query, connection))
{
// add parameters and their values
cmd.Parameters.Add(new SqlParameter("SkillName", skills.SkillName ));
cmd.Parameters.Add(new SqlParameter("SkillNumber", skills.SkillNumber ));
cmd.Parameters.Add(new SqlParameter("SkillLastUpdated", skills.LastUpdated ));
cmd.Parameters.Add(new SqlParameter("SkillServer", skills.CallServer
cn.Open();
cmd.ExecuteNonQuery();
}
}
you forgot to set the connection property for the command object: command.Connection = connection;
and:
command.CommandType = CommandType.Text;
command.CommandText = your_sql_query;
See: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.connection(v=vs.110).aspx

C# simple code to write an INSERT query is giving an exception

I have a very basic and beginner problem. I got a 5 line code and I got exception in that.
My database :
It has one table and two columns inside the table viz. id and name.
I made a form.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
SqlConnection conn = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename=\"C:\\Users\\Nicki\\documents\\visual studio 2012\\Projects\\WindowsFormsApplication2\\WindowsFormsApplication2\\Database2.mdf\";Integrated Security=True");
conn.Open();
SqlCommand command = new SqlCommand("INSERT INTO Table (id,name) VALUES (1,'" + textBox1.Text + "')", conn);
command.ExecuteNonQuery();
conn.Close();
}
I get the following exception on running the code:
It says that I have syntax error even though the syntax error is correct. Any help would be appreciated.
Thankyou!
You should use a using clause to properly manage resources and use parameters to avoid security problems. It is not recommended to use reserved words as "table". Try this:
const string commandText = "INSERT INTO [Table] (id,name) VALUES (1,#Name)";
using (SqlConnection connection = new SqlConnection(ConnectionString))
{
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#Name", SqlDbType.VarChar);
command.Parameters["#Name"].Value = textBox1.Text;
connection.Open();
var rowsAffected = command.ExecuteNonQuery();
}

Error running SQL query on C# - OleDbException was unhandled, characters found after end of SQL statement

Whenever I run the below event on C# I get the following error message - OleDbException was unhandled, characters found after end of SQL statement at the int affectedRows = (int)command.ExecuteNonQuery(); line. Any idea how I can fix it?
private void save_btn_Click(object sender, EventArgs e)
{
if (pgpText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: PGP");
}
else if (teamText.Text.Trim().Length == 0)
{
MessageBox.Show("Please fill the following textbox: Team");
}
else
{
using (OleDbConnection conn = new OleDbConnection())
{
string pgp = pgpText.Text;
string team = teamText.Text;
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='db.mdb'";
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "UPDATE PGP SET PGP=pgp,Team=team WHERE pgp=pgp; SELECT ##ROWCOUNT;";
conn.Open();
int affectedRows = (int)command.ExecuteNonQuery();
if (affectedRows == 0)
{
command.CommandText = "INSERT INTO PGP (PGP,Team) VALUES (pgp,team)";
command.ExecuteNonQuery();
}
}
}
}
I suspect you were actually trying to use parameters - note that your pgp and team variables in C# aren't being used at all in your code. I suspect you want something like:
using (OleDbConnection conn = new OleDbConnection())
{
string pgp = pgpText.Text;
string team = teamText.Text;
conn.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source='db.mdb'";
OleDbCommand command = new OleDbCommand();
command.Connection = conn;
command.CommandText = "UPDATE PGP SET Team=? WHERE PGP=?";
command.Parameters.Add("team", OleDbType.VarChar).Value = team;
command.Parameters.Add("pgp", OleDbType.VarChar).Value = pgp;
conn.Open();
int affectedRows = (int) command.ExecuteNonQuery();
if (affectedRows == 0)
{
command.CommandText = "INSERT INTO PGP (Team, PGP) VALUES (?, ?)";
// Parameters as before
command.ExecuteNonQuery();
}
}
Note that I've removed the "SELECT ##ROWCOUNT" part from your update - that's not needed as ExecuteNonQuery returns the number of rows affected anyway.
A couple of other notes:
For most database providers, you'd use named parameters instead of positional ones, e.g. VALUES (#pgp, #team) and then use the parameter names... but the OLE DB provider in .NET doesn't support these.
Do not use string concatenation for SQL as another answer (possibly deleted by the time you read this) has suggested - that paves the way for SQL Injection attacks and conversion issues. (And it's messy.)

C# MySql.Data INSERT INTO error

I use the MySql.Data in c# for a mysql connection. On another program it worked but currently i'm hanging on the INSERT INTO command.
I get the following error:
An unhandled exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll
Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'key) VALUES ('PGJWZBPOWTRPUTKY')' at line 1
With this code:
MySqlCommand Command = Connection.CreateCommand();
MySqlDataReader Reader;
Command.CommandText = "INSERT INTO jt_teamsync (key) VALUES ('" + TeamSyncKey + "')";
Connection.Open();
Reader = Command.ExecuteReader();
Connection.Close();
Thanks for any help
KEY is a reserved keyword in mysql. It should be escaped using backtick,
INSERT INTO jt_teamsync (`key`) VALUES(...)
MySQL Reserved Keywords List
As a sidenote, your query is very weak. It is vulnerable with SQL Injection. Parameterized the value to avoid from it, eg
string content = TeamSyncKey;
string connStr = "connection string here";
string sqlStatement = "INSERT INTO jt_teamsync (`key`) VALUES (#key)";
using (MySqlConnection conn = new MySqlConnection(connStr))
{
using(MySqlCommand comm = new MySqlCommand())
{
comm.Connection = conn;
comm.CommandText = sqlStatement;
comm.CommandType = CommandType.Text;
comm.Parameters.AddWithValue("#key", content);
try
{
conn.Open();
comm.ExecuteNonQuery();
}
catch(MySqlException e)
{
// do something with the exception
// do not hide it
// e.Message.ToString()
}
}
}

Error in asp.net c# code (mysql database connection)

My code is to update a record if it already exists in database else insert as a new record.
My code is as follows:
protected void Button3_Click(object sender, EventArgs e)
{
OdbcConnection MyConnection = new OdbcConnection("Driver={MySQL ODBC 3.51 Driver};Server=localhost;Database=testcase;User=root;Password=root;Option=3;");
MyConnection.Open();
String MyString = "select fil_no,orderdate from temp_save where fil_no=? and orderdate=?";
OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
MyCmd.Parameters.AddWithValue("", HiddenField4.Value);
MyCmd.Parameters.AddWithValue("", TextBox3.Text);
using (OdbcDataReader MyReader4 = MyCmd.ExecuteReader())
{
//**
if (MyReader4.Read())
{
String MyString1 = "UPDATE temp_save SET order=? where fil_no=? AND orderdate=?";
OdbcCommand MyCmd1 = new OdbcCommand(MyString1, MyConnection);
MyCmd1.Parameters.AddWithValue("", Editor1.Content.ToString());
MyCmd1.Parameters.AddWithValue("", HiddenField1.Value);
MyCmd1.Parameters.AddWithValue("", TextBox3.Text);
MyCmd1.ExecuteNonQuery();
}
else
{
// set the SQL string
String strSQL = "INSERT INTO temp_save (fil_no,order,orderdate) " +
"VALUES (?,?,?)";
// Create the Command and set its properties
OdbcCommand objCmd = new OdbcCommand(strSQL, MyConnection);
objCmd.Parameters.AddWithValue("", HiddenField4.Value);
objCmd.Parameters.AddWithValue("", Editor1.Content.ToString());
objCmd.Parameters.AddWithValue("", TextBox3.Text);
// execute the command
objCmd.ExecuteNonQuery();
}
}
}
I am getting the error as:
ERROR [42000] [MySQL][ODBC 3.51 Driver][mysqld-5.1.51-community]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'order,orderdate) VALUES ('04050040272009',' &' at line 1
The datatype for fields in table temp_save are:
fil_no-->INT(15)( to store a 15 digit number)
order-->LONGTEXT(to store contents from HTMLEditor(ajax control))
orderdate-->DATE(to store date)
Please help me to resolve my error.
order is a reserved word. For a complete list of Reserved Words, please review this document.
You can wrap it in back-ticks i.e.
(on my keyboard a back tick is under the ~ key)
INSERT INTO temp_save (fil_no,`order`,orderdate)....
i would try brackets in case ... that's the way it works in ms sql server .. probablly the same in mySql
String MyString1 = "UPDATE temp_save SET [order]=? where fill .... ";

Categories