Insert date in dd-MM-yyyy format - c#

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?

Related

Generic SQL UPDATE clause suitable for mutliple data types

Fairly new to SQL. Say I have a table with field1 of type string (VARCHAR) and field2 of type integer (INTEGER). As I understand it, you're supposed to use ='newValue' for string fields, and =newValue for integer fields (and =#newValue# for date fields).
Is there a trick that allows generic construction of the SET clause without needing to know the type of the field being updated in advance?
void UpdateDatabase(string field, string oldValue, string newValue)
{
// Construct without needing work out whether '', ## or (nothing) is required?
string sqlUpdate = (
"UPDATE MyTable" +
" SET " + field + " = " + newValue +
" WHERE " + field + " = " + oldValue);
// Execute the statement on the database
}
This might be used as follows:
UpdateDatabase("field1", "Danger Mouse!", "Mickey Mouse");
UpdateDatabase("field2", "15", "7");
Your code will need to be a lot more complex if you want to predetermine the datatypes of the fields you're inserting into.
Most SQL flavours have some kind of catalog, so for example on MS SQL Server you would need do something like:
SELECT DATA_TYPE FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = 'MyTable' AND COLUMN_NAME = 'field'
For every column you're about to write to, then apply the single-quote or not as per the data type.
There's ways and means of doing this, and depending on how many different fields you want to write at the same time will depend how complex the logic has to be to get the column datatypes.
For a large number of columns ideally you would gather all the column names you're about to write to into a table first, then use that table to query the datatypes
However, in SQL Server you can normally get away with putting single-quotes around everything, even integers and floats. SQL Server will intelligently remove the single quotes as needed.
It looks like you're using MySQL since you're required to put hashes around dates, in which case I am sorry for your loss.

How do you Allow the user to search for a date in a database, showing them all relevant information c#

I want to allow the user to search for a specific date (using a text box) and for the database to show them all entered information within that date. I have already compiled the query, show below:
SELECT Date, ([Test result]),
FROM [User/Test]
WHERE Date Like '%' + #value + '%'
I have used a data grid view on a phone to allow the user to visually see the search, incorporated a text box and search button and I have used the code below behind this button:
this.user_TestTableAdapter.search(this.questionareDataSet1._User_Test, textBox1.Text);
The error I get is that a varchar can't be compared with a date, which I understand. Do I need to convert the date to string to enable the search to take place?
Thanks.
Force formatting to a date "safe" format on the input field (look into the jQuery datepicker method for websites).
var selectedDate = Convert.ToDateTime(txtInputDate.Value);
var sql = " SELECT * FROM table WHERE datefield BETWEEN '" + selectedDate.ToString("yyyy-MM-dd") + "' AND NOW();";
You can also do things like...
var dateAddDaysValue = 2;
var sql = " SELECT * FROM table WHERE datefield BETWEEN '" + selectedDate.ToString("yyyy-MM-dd") + "' AND '" + selectedDate.AddDays(dateAddDaysValue).ToString("yyyy-MM-dd") + "';";
Cheerio!
Edit: You should be aware that this method of building SQL queries is extremely vulnerable to injection. Make sure you are properly sanatizing your queries.

Covert C# Datetime to MySql DateTime format

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

Select data based on date using SQL in C# to retrieve data from VFP db

We are using Abra Suite Software that is using a VFP db. I have a small program in C# that I would like to use to retrieve data from the db and generate a csv file from it. At this point my problem is to get the data based on the range of date that I specified in the SQL statement. Below is my SQL statement and for whatever reason I see that there are records from 2008 (i.e. 06/09/2008). What am I doing wrong here? Because when I read how SQL works I should have been able to do "WHERE chkdate BETWEEN '2007-06-01' '2007-06-06'" but I always get 'Operator/operand type mismatch', that's why I am using CAST in my current SQL statement.
string SelectCmd = "SELECT TOP 100 p_empno, p_fname, p_lname, chknumber, chkamount, CAST(chkdate AS varchar(10)) " +
"FROM hrpersnl " +
"INNER JOIN prckhist ON hrpersnl.p_empno = prckhist.empno " +
"WHERE CAST(chkdate AS varchar(10)) BETWEEN '06/06/2007' AND '06/09/2007' " +
"ORDER BY p_empno";
Put braces instead of apostrophes around your two between dates, like {06/06/2007} AND {06/09/2007}

Updating Excel Cell with Non-Numeric Data in C#

I have a query that is
ExcelQuery = "Update [Sheet1$] "
+"set CITIZEN_ID = #" + value
+ " where CITIZEN_ID = " + value;
As you can see, I'm essentially just prepending a "#" to the CITIZEN_ID field. value is a int/numeric value. So if I had "256" in the CITIZEN_ID column it would be converted to "#256"
When I execute this I get an OleDbException Syntax error in date in query expression so I surrounded part of the query in single quotes like this,
ExcelQuery = "Update [Sheet1$] "
+"set CITIZEN_ID = '#" + value + "' "
+"where CITIZEN_ID = " + value;
With that I get yet another OleDbException this time with, Data type mismatch in criteria expression.
I'm guessing for some reason the CITIZEN_ID fields don't want to take anything besides a plain number. Is there any way I can remedy this to get that pound symbol in?
Thanks!
Can't you just change the number format so it shows a '#' before each number in the CITIZEN_ID field.
This doesn't solve your stated problem .. but it avoids it :-)
Update:
This StackOverflow Question ( excel-cell-formatting) talks about cell formatting using C#
It sounds like you are trying to use SQL to INSERT a text value into a column which the DBMS (the Access Database Engine) sees as DOUBLE FLOAT and hence getting a type mismatch error. You may be able to change registry values to convince the engine to consider the column to be text, see:
External Data - Mixed Data Types

Categories

Resources