I am inserting data into MySql from C# code in Windows Forms application. This work fine on my development machine. when I move the code to other machine to test I get the error of
string was not recognized as valid datetime
I have tried with every solution TryParse, ParseExact, TryParseExact even Convert function. in last I tried to done with direct in query to skip further problems.
string dd = row["TIMESTAMP1"].ToString(); // 14-Nov-2018 02:25:00 AM
DateTime dt1 = DateTime.ParseExact(dd, "dd-MMM-yy h:mm:ss tt", null);
//string date2 = dt1.ToString("yyyy-MM-dd hh:mm:ss");
string y = dt1.Year.ToString();
string m = dt1.Month.ToString();
string d = dt1.Day.ToString();
string h = dt1.Hour.ToString();
string i = dt1.Minute.ToString();
string s = dt1.Second.ToString();
string dte = y + "," + m + "," + d + "," + h + "," + i + "," + s;
//DateTime.TryParseExact(date2, "yyyy-MM-dd hh:mm:ss", new CultureInfo("en-US"), DateTimeStyles.None, out dateDb);
//DateTime date3 = DateTime.Parse(date2, "yyyy-MM-dd hh:mm:ss");
string query = "INSERT INTO transaction (transid, ticketid, storeid, TIMESTAMP, transtypeid, total) Values ('" + row["transid"] + "','" + row["ticketid"] + "','" + Convert.ToInt32(row["storeid"]) + "',STR_TO_DATE('"+dte+ "', '%Y,%m,%d,%h,%i,%s'),'" + Convert.ToInt32(row["transtypeid"]) + "','" + Convert.ToDecimal(row["total"]) + "')";
How do I make this possible to work on other machines without exceptions. It works fine on development machine.
Update
tried with parameters too
cmd.Parameters.Add(new MySqlParameter("#date", date2)).MySqlDbType = MySqlDbType.DateTime;
Related
//I have this code and I want to insert only the date in the database without //the time, but this will always store value like this: 2019-10-19 00:00:00.000.
SqlCommand cmd2 = conn.CreateCommand();
cmd2.CommandType = CommandType.Text;
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
string time1 = TextBox_DepartureTime.Text + " " + DropDownListAMPM.SelectedValue;
string time2 = TextBox_ArrivalTime.Text + " " + DropDownList_AMPM2.SelectedValue;
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
if (date <= DateTime.Now.Date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Departure Date Cannot be in the past";
}
else
{
if (date2 <= date)
{
Label_EditTableMessage.ForeColor = System.Drawing.Color.Red;
Label_EditTableMessage.Text = "Return Date Cannot be Less than the Departure Date";
}
else
{
cmd2.CommandText = "insert into flight(airline_id,flight_number,numer_seats,departure_city,destination_city,departure_time,arrival_time,departure_date,arrival_date) values( '" + DropDownList_AirlineId.SelectedValue + "','" + TextBox_FlightNumber.Text + "','" + TextBox_NumerSeats.Text + "', '" + TextBox_DepartureCity.Text + "', '" + TextBox_DestinationCity.Text + "', '" + time1 + "', '" + time2 + "', '" + dateOnly1 + "', '" + dateOnly2 + "') ";
cmd2.ExecuteNonQuery();
Label_EditTableMessage.ForeColor = System.Drawing.Color.Green;
Label_EditTableMessage.Text = "Flight Added";
EmptyTextBoxes();
GridView_Flight.DataBind();
}
}
}
The problem is not with your code. You should change the data type of your field in the database. Instead of datetime or datetime2 you should use date.
You can refer to this article: https://learn.microsoft.com/en-us/sql/t-sql/functions/date-and-time-data-types-and-functions-transact-sql?view=sql-server-ver15#DateandTimeRelatedTopics
2 parts to this:
Your schema probably has the column data type set to DATETIME instead of just DATE which is going to cause it to store the full date and time regardless. This is the first thing I would check.
In your C# you can use the .Date property on a DateTime object to get just the date part of it. This is irrelevant if you use the correct data type for your column as per point 1
date.Date
or if you want it in string format:
date.Date.ToShortDateString()
the problem is you use
DateTime dateOnly1 = date.Date;
DateTime dateOnly2 = date2.Date;
and previus you use
DateTime date = DateTime.ParseExact(TextBox_DepartureDate.Text, "dd/MM/yyyy", null);
DateTime date2 = DateTime.ParseExact(TextBox_ArrivalDate.Text, "dd/MM/yyyy", null);
you are working only with date, and the datetime assume the time with 00:00:00
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.
It is possible to auto-increment datetime which I parse from daterangepicker to add AddDays(7) and then insert it to DB?
string strValue = Page.Request.Form["daterange"];
string strValue2 = Page.Request.Form["daterange2"];
DateTime myDate = DateTime.Parse(strValue);
DateTime myDate2 = DateTime.Parse(strValue2);
queryStr = "INSERT INTO `wp_reservations` ( `arrival`, `departure`, `user`, `name`, `email`, `country`, `approve`, `room`, `roomnumber`, `number`, `childs`, `price`, `custom`, `customp`, `reservated`) VALUES ('" + strValue + "INTERVAL 7 DAY', '" + strValue2 + "', 0, '" + DropDownList1.SelectedItem.Text + "', '" + emailValue + "', 'SI', '" + DropDownList2.SelectedValue + "', '" + DropDownList3.SelectedValue + "', '1', 10, 0, '0;0', '', '', '" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss tt") + "');";
You can use
DATE_ADD(NOW(), INTERVAL 7 DAY) in insert query
If u want to do this in code see Datetime in C# add days
U can also do it in DAO query see DATEADD (Transact-SQL)
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
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");