Errors when inserting date and time into QODBC query C# - 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.

Related

ASP.net MVC: Input String Was Not In Correct Format

I'm trying to write to a database and am getting the "Input String Was Not In Correct Format" error. I'm assuming it's the data types on the last two columns but I'm not sure how to change. In SQL Server, they are both of the money datatype. Code below:
string query = null;
for (int i = 0; i < result.Tables[0].Rows.Count; i++)
{
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
query = "INSERT INTO Upload(Email, TimeStamp, EmployeeId, Name, Title, Department, Race, Gender, AnnualizedBase, AnnualizedTCC) VALUES ('"
+ System.Web.HttpContext.Current.User.Identity.GetUserId() + "', "
+ " '" + DateTime.Now + "', "
+ " '" + result.Tables[0].Rows[i][0].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][1].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][2].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][3].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][4].ToString() + "', "
+ " '" + result.Tables[0].Rows[i][5].ToString() + "', "
+ Convert.ToInt32(result.Tables[0].Rows[i][6]) + ", "
+ Convert.ToInt32(result.Tables[0].Rows[i][7])
+ ")";
con.Open();
SqlCommand cmd = new SqlCommand(query, con);
cmd.ExecuteNonQuery();
con.Close();
}
The error Input string was not in correct format is most likely caused by one of the values in your column not being convertible to an int. If the datatype in SQL is money then you should try and convert to a decimal and not an int. Try this for each row:
decimal num;
if (decimal.TryParse(result.Tables[0].Rows[i][6], out num))
{
// use num because it is indeed a decimal (money in SQL)
}
else
{
// What do you want to do? Log it and continue to next row?
}
Also please read Bobby Tales and example of paratmetrized query.

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) )');";}

syntax error in query

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.

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