Unable to insert DateTime format into database - c#

I'm unable to insert the DateTime into my database. Am i writing the statement wrongly?
Apparently without the DateTime, I am able to insert into the database
string dateAndTime = date + " " + time;
CultureInfo provider = CultureInfo.InvariantCulture;
DateTime theDateTime = DateTime.ParseExact(dateAndTime, "d MMMM yyyy hh:mm tt", provider);
//Create a connection, replace the data source name with the name of the SQL Anywhere Demo Database that you installed
SAConnection myConnection = new SAConnection("UserID=dba;Password=sql;DatabaseName=emaDB;ServerName=emaDB");
//open the connection
; myConnection.Open();
//Create a command object.
SACommand insertAccount = myConnection.CreateCommand();
//Specify a query.
insertAccount.CommandText = ("INSERT INTO [meetingMinutes] (title,location,perioddate,periodtime,attenders,agenda,accountID,facilitator,datetime) VALUES ('"+title+"','" + location + "', '" + date + "','" + time + "', '" + attender + "','" + agenda + "', '" + accountID + "','" + facilitator + "','" +theDateTime+ "')");
try
{
insertAccount.ExecuteNonQuery();
if (title == "" || agenda == "")
{
btnSubmit.Attributes.Add("onclick", "displayIfSuccessfulInsert();");
//ScriptManager.RegisterStartupScript(this, GetType(), "error", "alert('Please ensure to have a title or agenda!');", true);
}
else
{
btnSubmit.Attributes.Add("onclick", "displayIfSuccessfulInsert();");
Response.Redirect("HomePage.aspx");
//ScriptManager.RegisterStartupScript(this, this.GetType(), "Redit", "alert('Minutes Created!'); window.location='" + Request.ApplicationPath + "/HomePage.aspx';", true);
}
}
catch (Exception exception)
{
Console.WriteLine(exception);
}
finally
{
myConnection.Close();
}
It does not insert the SQL into my database.
PS: theDateTime for example, may a value which is 7/14/2012 1:35:00 AM. How to insert this into the database??

Yes, you should write the query with parameters {0}, {1}, etc, and then use Parameters.Add.
insertAccount.CommandText = ("INSERT INTO [meetingMinutes]
(title,location,perioddate,periodtime, ...)
VALUES (?,?,?,?, ... )");
insertAccount.Parameters.Add( ... );
This will ensure that the SQL gets formed with correct syntax; and also prevent SQL injection attacks.

First of all NEVER use string concatenation for SQL queries or commands. Use parameters.
If you will use parameters then:
it is not possible to make sql-injection
query text and plan is cached, which increases performance
and what is important in your case - you do not have to think about formatting of the value, just pass the DateTime variable as the parameter
And also crosscheck that your DB column has datetime2 type, otherwise most likely you will not be able to store values less than 1 Jan 1758 (e.g. DateTime.MinValue).

Dont use quotes for yr date, remove all quotes where you are using a date
change ,'" +theDateTime+ "') to ," +theDateTime+ ")
and also secure yr sql cause it unsave for SQL injections

Related

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.

How to write SQL to display short date and time

I'm building a web application in asp.net using C# and postgreSQL database. The application is a booking system for appointments.
In a listbox I print the date, time and name of a certain appointment. I get get the date, time and name from the database.
My problem is that the date and time displays in long format, see picture below.
I want to display date in format 2014-04-22 and time in format 08:00.
My code:
string sql = "SELECT date, time, name FROM tbl_app WHERE id = '" + id + "'";
NpgsqlCommand command = new NpgsqlCommand(sql, conn);
NpgsqlDataReader dr = command.ExecuteReader();
while (dr.Read())
{
Listbox.Items.Add(dr["date"] + " " + dr["time"] + " " + dr["name"]);
}
Not really sure how the formatting could be done at Postgres end, but the fields appear to be of type DateTime, you can format the DateTime objects in your C# code like:
while (dr.Read())
{
//Check for DBNull.Value
DateTime date = Convert.ToDateTime(dr["date"]);
DateTime time = Convert.ToDateTime(dr["time"]);
Listbox.Items.Add(date.ToString("yyyy-MM-dd", CultureInfo.InvariantCulture) + " "
time.ToString("HH:mm", CultureInfo.InvariantCulture) + " "
+ dr["name"]);
}
Consider using parameter with your Query instead of concatenating your query. This is prone to SQL Injection. You may see: Custom Date and Time Format Strings
You can use ToShortDateString and ToShortTimeString which work on strings, which is why I used ToString on the DataReader items
while (dr.Read())
{
Listbox.Items.Add(dr["date"].ToString().ToShortDateString() + " " + dr["time"].ToString().ToShortTimeString() + " " + dr["name"]);
}
http://msdn.microsoft.com/en-us/library/system.datetime.toshorttimestring.aspx
http://msdn.microsoft.com/en-us/library/system.datetime.toshortdatestring.aspx
Edit
As the comment points out ToShortDateString does exist on Strings, instead it's applied to DateTime values... Code updated to show how
while (dr.Read())
{
Listbox.Items.Add(
DateTime.Parse(dr["date"].ToString()).ToShortDateString() + " " +
DateTime.Parse(dr["time"].ToString()).ToShortTimeString() + " " +
dr["name"]);
}

MySQL command - bug with dates

I am trying to put together the following MySqlCommand.
string cols = "(DateTime, Ticker, Open, High, Low, Close, Volume, ReqCode, UpdateTime)";
string parametrs = "(?DateTime, ?Ticker, ?Open, ?High, ?Low, ?Close, ?Volume, ?ReqCode, ?UpdateTime)"; //, ?UpdateTime)";
try {
using (MySqlCommand cmd = new MySqlCommand()) {
cmd.Connection = myConn;
cmd.CommandText = "INSERT INTO " + schema + cols + " VALUES" + parametrs + "\n ON DUPLICATE KEY UPDATE ReqCode = ?ReqCode AND UpdateTime = ?UpdateTime";
cmd.Parameters.Add("?DateTime", MySqlDbType.DateTime).Value = aPriceBar.BarTimestamp;
cmd.Parameters.Add("?Ticker", MySqlDbType.VarChar).Value = aPriceBar.Ticker;
cmd.Parameters.Add("?Open", MySqlDbType.Decimal).Value = aPriceBar.Open;
cmd.Parameters.Add("?High", MySqlDbType.Decimal).Value = aPriceBar.High;
cmd.Parameters.Add("?Low", MySqlDbType.Decimal).Value = aPriceBar.Low;
cmd.Parameters.Add("?Close", MySqlDbType.Decimal).Value = aPriceBar.Close;
cmd.Parameters.Add("?Volume", MySqlDbType.UInt32).Value = aPriceBar.Volume;
cmd.Parameters.Add("?ReqCode", MySqlDbType.VarChar).Value = aPriceBar.ReqCode;
cmd.Parameters.Add("?UpdateTime", MySqlDbType.DateTime).Value = aPriceBar.ReqTimestamp;
cmd.ExecuteNonQuery();
}
} catch (MySqlException ex) {
Console.WriteLine(ex.Message);
}
When I run the program, I catch the following exception:
"You have an error in your SQL syntax; ... for the right syntax to use
near ''2013-10-28 16:23:26.379'
I know for sure that 2013-10-28 is the date in ReqTimestamp.
I am surprised because the INSERT query goes through when I do not add to the query a reference to the UpdateTime column: the query uses successfully the DateTime type with one other column (Datetime). However, a) aPriceBar.ReqTimestamp is a DateTime, where reqTimestamp = DateTime.UtcNow while b) aPriceBar.BarTimestamp has been generated by
DateTime datetime = DateTime.ParseExact(sFields[0], "yyyy-MM-dd HH:mm:ss", CultureInfo.InvariantCulture);
''2013-10-28 16:23:26.379': the ".379" after the day make me suspect that when I use UctNow, instead of ParseExactsome with CultureInfo.InvariantCulture, some timezone information is added to the DateTime instance.
I checked the table definition with MySQL workbench and it looks allright.
Not sure how to fix this.
Thanks!
if your db field is "datetime" instead of datetime2 /offset it could be a problem with the xxx:xxx.379 part.
I figured it out.
The problem is actually with the SQL query syntax.
cmd.CommandText = "INSERT INTO " + schema + cols + " VALUES" + parametrs + "\n ON DUPLICATE KEY UPDATE ReqCode = ?ReqCode AND UpdateTime = ?UpdateTime";
ON DUPLICATE KEY UPDATE does not support AND but requires a comma instead (http://dev.mysql.com/doc/refman/5.0/en/insert-on-duplicate.html)
cmd.CommandText = "INSERT INTO " + schema + cols + " VALUES" + parametrs + "\n ON DUPLICATE KEY UPDATE ReqCode = ?ReqCode , UpdateTime = ?UpdateTime";
I did not figure it out earlier because I have not yet found a way to see the final query string and check how the placeholders are replaced by the parameters in the query.
Thank you all for your help.

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.

Visual studio 2008 datetimepicker to oracle date and timestamp

im trying to insert data into my oracle database but i am getting "invalid month" error as
it seems that i cant convert the datetimepicker value of my form into oracle date or timestamp(7) please help!
my code
dateTimePicker1.Format = DateTimePickerFormat.Custom;
dateTimePicker1.CustomFormat = " dd MM yyyy ";
string m = "insert into member(memberid,name,street,roadno,houseno,phoneno,joindate,sex) values(member_deptno.nextval,'" + a + "','" + b+ "','" + c + "','" + d + "','" + h + "','" + dateTimePicker1.Value.Date+ "','"+de+"')";
user parameterized sql insert.
e.g. parameterized select query
SqlConnection objConnection = new SqlConnection(connectionString);
objConnection.Open();
SqlCommand objCommand = new SqlCommand(
"SELECT * FROM User WHERE Name = #Name AND Password = #Password",
objConnection);
objCommand.Parameters.Add("#Name", tbName.Text);
objCommand.Parameters.Add("#Password", tbPassword.Text);
SqlDataReader objReader = objCommand.ExecuteReader();
As others have mentioned parameters are the way to go but I don't think they'll solve your issue.
I assume the CustomFormat shown in your snippet is the format Oracle wants. The problem is that when you call dateTimePicker1.Value.Date it gives you a DateTime object and since you're combining it with a string it executes the .ToString() method which results in a different format. You should put your format string in the .ToString() to control the output. Example:
dateTimePicker1.Value.Date.ToString("dd MM yyyy");

Categories