I have been trying to figure out how to add current datetime from c# into mysql column and that attribute/column is also in 'datetime' format. I am writing this code.
if (comboBox1.Text == "Cash On Delivery")
{
MessageBox.Show("Your order has been placed.","",MessageBoxButtons.OK);
string timeString = DateTime.Now.ToString("YYYY-MM-DD HH:MM:SS");
string constring = "datasource=localhost;port=3306;username=root;password=root";
string query = "insert into artgallery.payment_method where payment_method ='" +comboBox1.Text+ "' AND payment_date='" +formatForMySql+ "' AND payment_amount = '" +variables.total_amount+ "' ";
//rest of the code
}
I get this some syntax error related to the timeString Im trying to insert in my 'payment_date' column.
The right answer is to stop building your SQL like that to start with. Use parameterized SQL, then specify the DateTime value as the parameter value - you don't need a string representation at all in your code.
It's not immediately clear which driver you're using (there are two for MySQL, IIRC) but you should look at the Parameters property of whichever command type you're using.
It's really important to use parameterized SQL - not just to avoid conversion issues like this, but also to prevent SQL Injection Attacks. It also makes your code considerably simpler to read, in my view.
put it like this
INSERT INTO table_name( date_column) VALUES (STR_TO_DATE('2014-12-31 00:00:00','%Y-%m-%d %H:%i:%S')
Also, you put M (which mean of month ) in both month, and minute...
please recheck your format again here
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_date-format
Related
I have a table were processes are logged to and I want to create a console app that will loop and update the console as soon as the messages are written to the table.
The end result will be me looking at the console instead of querying the database.
I have a query that can pull the data and display, however I am looking for best practice/better solution as I feel mine is not up to standard
string ConnectionString = "connectionstring here";
string TableName = "table name here";
while (true)
{
SqlConnection myConnection = new SqlConnection(ConnectionString);
myConnection.Open();
SqlDataReader myReader = null;
SqlCommand myCommand = new SqlCommand("select LogDate, Message from " + TableName + " where convert(date, logdate, 103) = convert(date, getdate(), 103) order by logdate;", myConnection);
myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
Console.WriteLine(myReader["LogDate"].ToString() + " -> " +
myReader["Message"].ToString());
//Thread.Sleep(200);
}
myConnection.Close();
}
3 things I find worth mentioning:
Careful when building dynamic SQL by concatenating uncontrolled values. What happens if your TableName has a space in the middle (or worse, an SQL command like TableName; DECLARE #CurrentLogin VARCHAR(100) = SYSTEM_USER; EXEC('DROP LOGIN ' + #CurrentLogin);, do not execute!). Since you are dynamically changing the table, you can't parametrize this query, although there are some things you can to do reduce the risk of injection like making sure the TableName variable is less than X characters (usually 20 is enough), and doesn't contain spaces, semicolons or critical SQL words like EXEC or DROP.
You are selecting and filtering specific columns, so this query won't work on most tables, just the ones that have these columns. You should consider removing the dynamic table parameter and use a Switch instead, allowing only the tables you want to query to be queried. This will make your queries limited but safer.
Your filter is converting a table column (logdate) before doing a comparison to a constant (getdate()), this will make the index on logdate (if any) be inapplicable. I believe you want to see records of the current day, so you are making the comparison on the date code 103 (yyyy-MM-dd). You should avoid converting the table value and use a double filter instead, assuming that logdate is DATETIME. If logdate can't be on higher date than today you can skip the 2nd check:
WHERE
logdate >= CONVERT(DATE, GETDATE()) AND
logdate < CONVERT(DATE, GETDATE() + 1)
ORDER BY
logdate
The end result will be me looking at the console instead of querying
the database.
The console will query the database for you, you are just changing the user interface.
If you have many console logs, you can do a dynamic filtering by datetime instead of querying all the current date every time. So each query will bring records from the last datetime you queried, thus bringing all new records. You can do this by adding a full datetime parameter, only retrieving records higher than the previous one and storing the current datetime on this variable.
Instead of using a pull model and repeatedly querying the data even if there was no change, you could use a SqlDependency that notifies your application when a change occurs. This link contains an overview and a sample.
One thing to note though is that SqlDependency objects were built with server applications in mind. It is not meant to be rolled out to lots of clients listening for changes. See this link for additional information.
I'm trying to insert date in dd-MM-yyyy format in c#. Query for inserting is
SqlCommand cmd_cust = new SqlCommand(#"insert into custdetail values ('" + txtInvoiceNo.Text + "','" + txtCustomerName.Text + "','" + txt_contact.Text + "', '" + txtAddress.Text + "', '" + txt_total_amt.Text + "', '" + dt_date.Value.ToString("dd-MM-yyyy") + "')", con_create);
con_create.Open();
cmd_cust.ExecuteNonQuery();
con_create.Close();
I have created table with column name date has datatype date. After inserting record the value in date column field is in yyyy-dd-MM format. I want this in dd-MM-yyyy format.
Do not try to concatenate a string to build a correct sql command.
This leads only to parsing problems and Sql Injection Attacks.
Use instead a parameterized query
int isok = 0;
try
{
// Now your query is more readable and there are no more formatting problems here
SqlCommand cmd_cust = new SqlCommand(#"insert into custdetail values
(#invNo,#custName,#contact,#address,#amount,#dt)",
con_create);
con_create.Open();
cmd_cust.Parameters.AddWithValue("#invNo",txtInvoiceNo.Text );
cmd_cust.Parameters.AddWithValue("#custName",txtCustomerName.Text );
cmd_cust.Parameters.AddWithValue("#contact",txt_contact.Text);
cmd_cust.Parameters.AddWithValue("#address",txtAddress.Text.Text);
// The following parameter could require a conversion if the db field is not of text type
// cmd_cust.Parameters.AddWithValue("#amount", Convert.ToDecimal(txt_total_amt.Text));
cmd_cust.Parameters.AddWithValue("#amount", txt_total_amt.Text);
cmd_cust.Parameters.AddWithValue("#dt",dt_date.Value );
isok= cmd_cust.ExecuteNonQuery();
con_create.Close();
}
Using a parameter you don't need to worry how to format a DateTime value to a string, you pass directly the DateTime value as expected by the database field. It is the framework job to correctly pass this value to the underlying database table.
This is true also for the other fields like the string ones. If your user types a single quote inside one of your textboxes you get a syntax error with the string concatenation. The quote typed by your user mistakenly closes the value leaving the remainder of the text as invalid sql text
(e.g. textCustomerName.Text = O'Brian becomes ....,'O'Brian' ,....)
I agree with Steve's answer above. But, to focus on your specific question, SQL does not store the date in a specific format - it stores it as two integers (in binary). Therefore, the date you see in the query window (or wherever else you are looking at it) does not matter; likewise, whatever format you attempt to insert into the database does not matter (as long as SQL server can parse it correctly). If you want the output to look a certain way, you can re-format to suit your needs on a SELECT query. Both SQL and C# have extensive date formatting methods.
Are you formatting the date in a SQL query output or a C# program output?
How do i format a insert statement with date time for this collation...
Currently:
string SQLst = "UPDATE [LASTUPDATE] SET last_update = '" + DateTime.Now.ToString("yyyy-MM-dd") + "'";
This works for Latin1_General_CI_AS but now on a different server i need this statment to work with server set to collation SQL_Latin1_General_CP1_CI_AS
this is the error i get:
The conversion of a char data type to a datetime data type resulted in an out-of-range datetime value
Don't perform the conversion at all. Instead, use paramterized SQL and set the value as a parameter. You should be using parameterized SQL for all your parameters, in order to avoid SQL injection attacks, conversion issues like this one, and to keep your code cleaner.
Avoid unnecessary string conversions in general. They're almost always a potential source of subtle errors.
Would be great if you do as #Jon Skeet said, but if you cant, than use CONVERT
string SQLst = "UPDATE [LASTUPDATE] SET last_update = CONVERT(datetime, '"+DateTime.Now.ToString("yyyy-MM-dd")+"', 120)
I have val MyDate in my C# program that contain today-date or null.
I have date field in my access 2007 - TdateOpen
I try to insert to the database like this:
SQL = "insert into MyCount(TdateOpen) values ('" + MyDate +"')";
and I get this error:
Data type mismatch in criteria expression
what can be the problem?
Coz in your SQL statement you are entering date as String . Instead of String it should be a date/date format.
Try to surround by # .
You will need to ensure that the date is in US order (mm/dd/yyyy) or ANSI/ISO order, whether you use dash or slash is not important, ANSI/ISO is to be preferred.
Then as, Madhu CM said, the delimiter for dates in Access is hash (#), however, your date can be null and null cannot be delimited, so you will either have to add the delimiter to a date string, if a date is returned, or use two sql statements, one for null and one for date.
You could SQL parameters instead of dynamically embedding the date value into the statement.
SQL = "insert into MyCount(TdateOpen) values (?)";
var parameter = yourCommand.CreateParameter();
parameter.Value = yourDateTime;
yourCommand.Parameters.Add(parameter);
(DISCLAIMER: The code was not compiled nor tested, but it should give you a hint)
I have Date Var in Oracle, and I try to insert Data from my C# program
sql = "insert into Table(MyDate) values (" + convert.todatetime(txt) + ")";
I get an Error, what can i do ?
cmd.CommandText = "INSERT INTO Table (myDate)VALUES(:dateParam)";
cmd.Parameters.Add(new OracleParameter("dateParam", OracleDbType.Date))
.Value = DateTime.Now;
cmd.ExecuteNonQuery();
Use parameters. It's going to solve your problem and prevent injection.
Oracle expects it to be an actual date value, not just a string that looks like a date. You have to use the TO_DATE() function to explain how your string is formatted, something like this:
INSERT INTO Table (myDate)
VALUES(TO_DATE('2009-03-30 12:30:00', 'YYYY-MM-DD HH:mi:ss'));
Try using DateTime.TryParse(text) or DateTime.Parse(text)
I know this was a poorly asked question, but I saw some poor answers when I had the same question and ran into this. This is how I solved it, and I'll answer using the OP's context:
Parse the date in to a DateTime variable:
DateTime myDate = DateTime.Parse(txt);
Then parameterize your query:
sql = "insert into Table(MyDate) values (:myDate)";
Set up an OracleParameter:
OracleParameter param = new OracleParameter();
param.ParameterName = "myDate";
param.OracleDbType = OracleDbType.Date;
param.Value = myDate;
Assuming you already have an OracleConnection as connection, set up your command and add your parameter:
OracleCommand cmd = new OracleCommand(sql, connection);
cmd.Parameters.Add(param);
Execute:
cmd.ExecuteNonQuery();
Do NOT waste your time on any of the TO_DATE nonsense. This is for when you are adding something using SQL*Plus or Oracle SQL Developer directly, or MAYBE where you want to send in a STRING variable's value (not a DateTime variable) in the EXACT format that TO_DATE expects and that you assign within the TO_DATE construct within your query or a stored procedure (i.e. to_date('2013-05-13 12:13:14', 'YYYY-MM-DD HH24:MI:SS'). Using a DateTime variable and assigning that to an OracleParameter with an OracleDbType of OracleDbType.Date, assuming you have a DATE field in your table and can parse txt into a DateTime variable, however, is best and easiest.
Easiest way possible:
DateTime inputDate = Convert.ToDateTime("01/01/2019"); //<---Input Sample Date in format
string queryParameters = String.Format("SELECT * FROM TABLE WHERE DATE = '{0}')", inputDate.ToString("dd-MMM-yyyy")); //<-- Converts System.DateTime into Oracle DateTime
//Forget looking anywhere else for an answer, copy and paste and reform this very code
//and see the results
Please bind your variables (like ocdecio tells) ! Not only does it prevent sql injection it is also much faster. Especially in a multi concurrency situation. Read for example here: http://download.oracle.com/docs/cd/B28359_01/appdev.111/b28844/building_odp.htm#CEGCGDAB .
"Bind variables are placeholders inside a SQL statement. When a database receives a SQL statement, it determines if the statement has already been executed and stored in memory. If the statement does exist in memory, Oracle Database can reuse it and skip the task of parsing and optimizing the statement. Using bind variables makes the statement reusable with different input values. Using bind variables also improves query performance in the database, eliminates the need for special handling of literal quotation marks in the input, and protects against SQL injection attacks."