syntax error in query - c#

I am new to programming and is developing a new desktop database applcation in Access, I am trying to insert data into a table. I had two datetime picker and I read the value from it as
jobcodedatabean.PaperRecievedate1 = dtpjobcodedate.Value.Date;
jobcodedatabean.Shipmenentdate = dtpshipmentdate.Value.Date;
and I had passed the databean to a function
public void addaction(JobCodeDataBean jobcodedatabean)
{
MessageBox.Show(jobcodedatabean.Shipmenentdate.ToString());
try
{
OleDbConnection oleDbConnection1 = new System.Data.OleDb.OleDbConnection(connString);
oleDbConnection1.Open();
OleDbCommand oleDbCommand1 = new System.Data.OleDb.OleDbCommand("INSERT INTO jobcodemastertable (jobcode ,customercode,totaltrip,shipmentdate,fromPlace, destination,description ,packagetype ,noofpackage ,contactperson ,jobecodedate ) Values ('" + jobcodedatabean.Jobcode + "', '" + jobcodedatabean.Customercode + "' ," + jobcodedatabean.Totaltrip + "," + jobcodedatabean.Shipmenentdate + " ,'" + jobcodedatabean.Fromplace + "','" + jobcodedatabean.Destination + "','" + jobcodedatabean.Description + "','" + jobcodedatabean.Typeofpackage + "','" + jobcodedatabean.Noofpackages + "','" + jobcodedatabean.Contactperson + "'," + jobcodedatabean.PaperRecievedate1 + ") ", oleDbConnection1);
oleDbCommand1.CommandType = CommandType.Text;
oleDbCommand1.ExecuteNonQuery();
oleDbConnection1.Close();
}
catch (Exception)
{
MessageBox.Show(e);
}
but i am getting the exception at the query
Syntax error (missing operator) in query expression '2/16/2012 12:00:00 AM'.
In access the date fields are in short date format
Please somebody help to sort out my mistake

Incorrect quotations. To avoid these kinds of mistakes, use ordered parameters:
var myCommand = new OleDbCommand(
"INSERT INTO MyTable(someDateField, someTextField, someNumberField) VALUES (?, ?, ?)"
);
myCommand.Parameters.Add(DateTime.Now);
myCommand.Parameters.Add("Some text");
myCommand.Parameters.Add(123);
Using parameters also helps protect against SQL injection attacks. In your example, if one of the strings contained an apostrophe, it would fail unless you correctly converted it to two apostrophes. With parameters these are escaped correctly automatically.

You forgot to enclose dates in quotes:
... ",'" + jobcodedatabean.Shipmenentdate + "' ,'" ...
... "','" + jobcodedatabean.PaperRecievedate1 + "') " ...
Note single quotes around both dates.

Related

How to fix "Invalid Column Name" SQL Exception on MSSQL

I am trying to pass both Column name and the Value to be checked in the code at runtime. However I am getting an:
"Invalid Column Name "
Exception. The code is as follows :
cmd = new SqlCommand();
con.Open();
cmd.Connection = con;
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi," +
"Ucret,Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) VALUES " +
"(" + isim + ",'" + soyisim + "','" + telefon + "'," +
"'" + oda_sayisi + "','" + kisi_sayisi + "','" + ucret + "'," +
"'" + aciklama + "','" + giris_tar + "','" + cikis_tar + "'," +
"'" + current_tarih + "')";
cmd.ExecuteNonQuery();
con.Close();
You've missed a single quote here " + isim + " and it should be '" + isim + "'. However you should always use parameterized queries to avoid SQL Injection and also to get rid of this kind of errors.
cmd.CommandText = "INSERT INTO rezervasyon (Ad,Soyad,TelefonNo,OdaSayisi,KişiSayisi,Ucret" +
",Acıklama,GirisTarihi,CikisTarihi,KayitTarihi) " +
"VALUES (#isim, #soyisim , ...)";
cmd.Parameters.AddWithValue("#isim", isim);
cmd.Parameters.AddWithValue("#soyisim", soyisim);
//Other parameters
Although specify the type directly and use the Value property is more better than AddWithValue:
cmd.Parameters.Add("#isim", SqlDbType.VarChar).Value = isim;
Can we stop using AddWithValue() already?

Errors when inserting date and time into QODBC query C#

I am getting an error
ERROR [42500] ERROR: 3020 - There was an error when converting the date value "0000-00-48. In the field "salesOrder Transaction Date
The date value I am trying to insert is 4/4/2018.
My code
DateTime JobDate = Wintac_JobDate;
string addSalesOrder = "INSERT INTO SalesOrderLine (CustomerRefListID, TemplateRefListID," +
" SalesOrderLineItemRefListID, SalesOrderLineDesc,SalesOrderLineQuantity, SalesOrderLineRate, " +
"SalesOrderLineSalesTaxCodeRefListID, Memo, SalesOrderLineInventorySiteRefListID, SalesOrderLineInventorySiteLocationRefListID" +
", TxnDate, ShipAddressAddr1, ShipAddressAddr2, ShipAddressAddr3, ShipAddressAddr4, ShipAddressAddr5, FQSaveToCache)" +
"VALUES('" + QBCustomerListID + "','" + templateLID + "', '" + LID + "', '" + Description + "', " + Quantity + ", " + 120 + "," +
" '" + SalesTax + "', '" +Wintac_WipNo+"','"+LaborSite+"','"+LaborSiteLocation+"',"+
"?,'" + shipAdr1+ "','" + shipAdr2 + "','" + shipAdr3 + "','" + shipAdr4 + "','" + shipAdr5 + "'," +
""+ FQSaveToCache + ")";
OdbcCommand sqlcmd2 = new OdbcCommand(addSalesOrder, quickbookscon2);
sqlcmd2.CommandType = CommandType.Text;
sqlcmd2.CommandTimeout = 180;
MessageBox.Show(JobDate.ToShortDateString());
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate
if (Quantity != 0)
{
if (sqlcmd2.ExecuteNonQuery() == 1)
{
if(FQSaveToCache == 0)
MessageBox.Show(" added successfully.");
}
}
sqlcmd2.Dispose()
I have tried converting the variable Job Date
Date Time
short date string
long date string
entering the variable directly into the query
Any help would be appreciated.
I think the main problem is on that line;
sqlcmd2.Parameters.Add("P7", OdbcType.DateTime).Value = JobDate.ToLongDateString()
You try to insert string representation on a DateTime typed column. That's quite wrong. You need to directly pass your DateTime value instead of passing it string representation. To learn this as a habit, please read Bad habits to kick : choosing the wrong data type
Other than this, I saw a few problem also in your code:
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Use using statement to dispose your connection and commmand automatically instead of callind Dispose method manually which you didn't even consider to do in your code.

C# insert into Access database

I have a simple user interface for an inventory database. The operation will be insert into, edit existing, view data grid, etc....There are a total of 4 fields for the inventory. The insert statement I am using works but if one of the entries does not have a value then it shows an error when trying to insert.
" Data type mismatch in criteria expression "
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtPart.Text + "','" + txtSerial.Text + "','" +
txtRO.Text + "','" + txtLocation.Text + "')";
I assume it is because the code needs a value for each field so how do I get around this issue?.
Actually when you trying to use this query you have said the First Parameter is SerialNumber and then PartNumber and when you are passing its reverse.
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtPart.Text + "','" +
txtSerial.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";
Due to this reason the fields you are entering have different size May be part number is bigger in size instead of SerialNumber or vice versa. So you should change it to
command.CommandText = "insert into Inventory(SerialNumber,PartNumber,ROnumber,Location)
values ('" + txtSerial.Text + "','" +
txtPart.Text + "','" +
txtRO.Text + "','" +
txtLocation.Text + "')";

SQlite insert not working

I'm writing a C# database winform app and I have a problem executing this query. It throws me this error:
SQLite error
near "SELECT": syntax error
Can someone help me please? Thanks for any answer or suggestion.
"INSERT into subor(idsubor, idpodfk, pnazovfk, datumpravop, podiel, podield, cislozLV,
datumzaradenia, idmajetok)
values (null, " + comboBox1.SelectedValue.ToString() + ",
'" + comboBox2.SelectedValue.ToString() + "',
'" + dateTimePicker1.Value.ToString("d. M. yyyy") + "',
'" + textBox2.Text + "',
" + podield.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture) + ",
'" + textBox4.Text + "',
'" + dateTimePicker2.Value.ToString("d. M. yyyy") + "',
SELECT IFNULL(a, '0') AS idmajetok
FROM (SELECT MAX(idmajetok) + 1 AS a FROM subor))";
Your C# string/SQLite SQL mixture still seems somewhat confusing, but one possible issue that I'm seeing is as follows:
You are using a SELECT statement to indicate one of the values in your VALUES list. As you can see in the syntax diagram, that SELECT statement has to be enclosed in parenthesis.
i suspect some SQL syntax Problem, and i made some changes to your select statement.
Please try out:
string sqlInsert = "INSERT into subor(idsubor, idpodfk, pnazovfk, datumpravop,
podiel,podield, cislozLV, datumzaradenia, idmajetok) values (null, '" +
comboBox1.SelectedValue.ToString() + "','" + comboBox2.SelectedValue.ToString() + "','" +
dateTimePicker1.Value.ToString("d.M.yyyy") + "','" + textBox2.Text + "','" +
podield.ToString("0.0000", System.Globalization.CultureInfo.InvariantCulture) + ",'" +
textBox4.Text + "','" + dateTimePicker2.Value.ToString("d.M.yyyy") + "','" + "SELECT
IFNULL(a, '0') AS idmajetok FROM (SELECT MAX(idmajetok) + 1 AS a FROM subor) )');";}

exception with nvarchar - data was truncated while converting from one data type to another

I'm having a bit of trouble with entering data into several columns of a database, all nvarchar types. I'm getting:
The data was truncated while converting from one data type to another. Name of function(if known)
DBConn.Open();
cmd = new SqlCeCommand("INSERT INTO [Employee Table] VALUES ('"+ social + "','" +
first + "','" + last + "','" + mid + "','" + address + "','" + phone + "',"
+ "'Employee'" + ",'" + city + "','" + state + "','" + zip + "','" + email + "','" + userName + "')", DBConn);
cmd.ExecuteNonQuery();
Any suggestions on how to avoid the truncating/converting error?
Your NVARCHAR isn't big enough to hold your string.
try using Parameters
SqlParameter param = new SqlParameter("Field", SqlDbType.NVarChar)
Param.Value = Field;
The reason is that the column's length is very short. So the value is longer than the maximum width of the column of the table.

Categories