I always have experienced this "INSERT INTO Statement" Syntax Error, can someone help me how to solve this?
try
try
{
OleDbConnection Con = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\MotoFix.mdb;");
Con.Open();
OleDbCommand Com = new OleDbCommand();
Com.Connection = Con;
Com.CommandText = "INSERT INTO Order VALUES ('" + txtRandomOrder.Text + "','" + txtCode.Text + "')";
Com.ExecuteNonQuery();
Con.Close();
}
catch (Exception ex)
{
XtraMessageBox.Show(ex.Message);
}
Guest UserPosted Jul 2, 2014, 6:35 AM
Com.CommandText = "INSERT INTO [Order] ...
Guest UserPosted Jul 2, 2014, 1:09 AM
Better approach to handle SQL DML operations is via ORM these days, if you want to adopt look for Petapoco or Massive. These code statements are not preferred approach because eg. if there is new column that's added then it needs code change & deploy.
And also these 'Insert' statements are messy and prone to single-quote or double quote menace
http://www.toptensoftware.com/petapoco/
Thnx
@SumitJolly
Ramesh MaruthiPosted Jul 1, 2014, 12:59 PM
{
string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=..\\MotoFix.mdb;";
InsertData(connectionString,
txtRandomOrder.Text.Trim(), -- RandomOrder
txtCode.Text .Trim(), -- Code
}
private void InsertData(string connectionString, string RandomOrder, string Code)
{
// define INSERT query with parameters
string query = "INSERT INTO Order VALUES (RandomOrder, Code) " +
"VALUES (@RandomOrder, @Code) ";
// create connection and command
using(OleDbConnection cn = new OleDbConnection(connectionString))
using(OleDbCommand cmd = new OleDbCommand(query, cn))
{
// define parameters and their values
cmd.Parameters.Add("@RandomOrder", SqlDbType.VarChar, 50).Value = RandomOrder;
cmd.Parameters.Add("@Code", SqlDbType.VarChar, 50).Value = Code;
// open connection, execute INSERT, close connection
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
Note : You should always use parameters in your query - NEVER EVER concatenate together your SQL statements.