insert date into SQL - c#

I'm trying to insert a date into a SQL table, but it when the program runs it gives the following error.
Conversion failed when converting date and/or time from character string.
string dateReleased = DateReleasedDate.Value.ToString("YYYY-MM-DD");
string myQuery = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, dateAdded, developerID, publisherID, consoleID) VALUES('"
+ GameNameTxt.Text + "', '" + GenreCombo.SelectedValue + "', '" + PlayersNUD.Value + "', '" + OnlineCombo.SelectedText + "', '"
+ dateReleased + "', 'GETDATE()', '" + DeveloperCombo.SelectedValue + "', '"
+ PublisherCombo.SelectedValue + "','" + ConsoleCombo.SelectedValue + "')";

Please use parametrized queries. My eyes hurt when I see string concatenations used to construct SQL queries:
using (var conn = new SqlConnection("SOME CONNECTION STRING"))
using (var cmd = new SqlCommand(conn))
{
conn.Open();
cmd.CommandText = "INSERT INTO GameTbl (gameName, genreID, players, online, dateReleased, developerID, publisherID, consoleID) VALUES (#gameName, #genreID, #players, #online, #dateReleased, #developerID, #publisherID, #consoleID)";
cmd.Parameters.AddWithValue("#gameName", GameNameTxt.Text);
cmd.Parameters.AddWithValue("#genreID", GenreCombo.SelectedValue);
cmd.Parameters.AddWithValue("#players", PlayersNUD.Value);
cmd.Parameters.AddWithValue("#online", OnlineCombo.SelectedText);
cmd.Parameters.AddWithValue("#dateReleased", DateReleasedDate.Value);
cmd.Parameters.AddWithValue("#developerID", DeveloperCombo.SelectedValue);
cmd.Parameters.AddWithValue("#publisherID", PublisherCombo.SelectedValue);
cmd.Parameters.AddWithValue("#consoleID", ConsoleCombo.SelectedValue);
var result = cmd.ExecuteNonQuery();
...
}
As far as the dateAdded column is concerned I would simply remove it from the INSERT and add it a default value directly in the SQL database.
Notice how you are directly passing DateTime instances and you leave ADO.NET handle the formats. As a bonus your code is safe against SQL injections.

DateReleasedDate.Value.ToString("yyyy-MM-dd");

The problem is you put GETDATE() into single-quotes. It is trying to convert the string 'GETDATE()' into a date.

The best way to pass a date into SQL from .net, IMO, is to use the .ToOADate function.
The function passes in a numerical representation of the date that will work on any database datetime \ date field regardless of the regional setup.
Some info for you: ToOADate

Related

Insert into access database Query Error in C#

OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
my_con.Open();
OleDbCommand o_cmd1 = my_con.CreateCommand();
o_cmd1.CommandText = "INSERT INTO Personal_Details(Date,Time,Patient_Name,Contact_Number,Gender,Allergic_To,KCO) VALUES ('" + DateTime.Now.ToString("dd-MM-yyyy") + "','" + DateTime.Now.ToString("h:mm:ss tt") + "','" + txtPatientName.Text + "','" + txtContactNo.Text + "','" + comboBoxGender.Text + "','" + txtAllergic.Text + "','" + txtKCO.Text + "')";
int j = o_cmd1.ExecuteNonQuery();
I am getting the Syntax error in Insert Statement I don't understand what is mistake if any one help me I am really thank full.Thanks in Advance.
Date and Time are typically reserved keywords in many database systems. You should at the very least wrap them with [ ]. More preferably, if you are designing the table, change the field name to something more descriptive. For example if the Date and Time represented a reminder then you could use ReminderDate and ReminderTime so as not to interfere with reserved keywords.
And follow the parameter advice that's already been given.
Use command parameters instead of concatenating strings. Your code is open for SQL Injection attacks or in your specific case the problem may be related with invalid user input. Try to thing about this situation:
What if the txtContactNo.Text returns this string "Peter's contact is +123456" ? How does the SQL query will look then? Pay close attention to ' character.
You should ALWAYS use parametrized SQL queries no matter how good you thing your input validation is. It also has more advantages like query plan caching etc.
So in your case the code must be written like this:
OleDbConnection my_con = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\\Users\\SS\\Documents\\131Current1\\125\\Current one\\ClinicMainDatabase.accdb");
using(my_con)
{
my_con.Open();
using(OleDbCommand o_cmd1 = my_con.CreateCommand())
{
o_cmd1.CommandText = #"
INSERT INTO Personal_Details ([Date], [Time], Patient_Name, Contact_Number, Gender, Allergic_To, KCO)
VALUES (#date, #time, #name, #contNo, #gender, #alergic, #kco)";
o_cmd1.Parameters.AddWithValue("#date", DateTime.Now.ToString("dd-MM-yyyy"));
o_cmd1.Parameters.AddWithValue("#time", DateTime.Now.ToString("h:mm:ss tt"));
o_cmd1.Parameters.AddWithValue("#name", txtPatientName.Text);
o_cmd1.Parameters.AddWithValue("#contNo", txtContactNo.Text);
o_cmd1.Parameters.AddWithValue("#gender", comboBoxGender.Text);
o_cmd1.Parameters.AddWithValue("#alergic", txtAllergic.Text);
o_cmd1.Parameters.AddWithValue("#kco", txtKCO.Text);
o_cmd1.ExecuteNonQuery();
}
}
Also make sure that you are properly disposing the connection and the command objects (by using :) the using keyword)
For more info read the docs in MSDN
https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparametercollection.addwithvalue(v=vs.110).aspx

Add date to sqlserver in yyyy-mm-dd

When i add the lastImportedDate(dd-mm-yyyy) with the following method to the sql server everything is fine. In the database the date is yyyy-mm-dd
But add the lastImportedDate(dd-mm-yyyy) with a different pc on the same server the day and month are switched. In the database the date is yyyy-dd-mm.
internal static void insertSelloutSales(string CustomerID, string type, DateTime lastImported, string periodStart, string periodEnd)
{
// Create SQL connection #connection
SqlConnection sqlConnection1 = new SqlConnection(Connection.connectionString());
SqlCommand cmd = new SqlCommand();
cmd.CommandType = CommandType.Text;
string periodstartQuery = periodStart;
string periodEndQuery = periodEnd;
// Create query with values and execute query
if (!periodStart.Equals("NULL"))
{
periodstartQuery = " '" + periodStart + "'";
}
if (!periodEnd.Equals("NULL"))
{
periodEndQuery = " '" + periodEnd + "'";
}
cmd.CommandText = "Insert into CarsSellout (CustomerID, type, lastImportedDate, PeriodStart, PeriodEnd) VALUES ('" + CustomerID + "', '" + type + "', '" + lastImported + "', " + periodstartQuery + ", " + periodEndQuery + ")";
cmd.Connection = sqlConnection1;
sqlConnection1.Open();
cmd.ExecuteNonQuery();
sqlConnection1.Close();
}
Note that the date settings on the pc's are both set as dd-mm-yyyy.
if you need more info please add a comment.!
What can be the problem in this case?
Do not insert your DateTime values with their string representations. Add your DateTime values directly to your parameterized queries.
SQL Server keeps your DateTime values in a binary format. They didn't have any format or something. What you saw them as yyyy-MM-dd or dd-MM-yyyy are just their textual representations.
Generating different string representations of a DateTime instance for different servers usually because they use different culture settings. But since you didn't show any relevant code that generates your strings, we never know.
Speaking of, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Please read carefully;
Bad habits to kick : choosing the wrong data type
As a best practice, use using statement to dispose your connections and commands automatically instead of calling Close methods manually.
using(var con = new SqlConnection(conString))
using(var cmd = con.CrateCommand())
{
// Define your CommandText with parameterized query.
// Define your parameters and their values. Add them with Add method to your command
// Open your connection
// Execute your query
}

Insert into DateTime (from C# to MySQL)

I Just Keep Having this Error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '2014-10-08 19:39:57)' at line 1
public string ObtenerFechaHora()
{
string query = "select CURRENT_TIMESTAMP() as Fecha";
OpenConnection();
MySqlCommand cmd = new MySqlCommand(query, connection);
cmd.ExecuteNonQuery();
DateTime e = (DateTime)cmd.ExecuteScalar();
CloseConnection();
return e.ToString("yyyy-MM-dd H:mm:ss");
}
Then i insert ("Fecha" is the DateTime Column)
string query = "INSERT INTO actividad (idTerminal, Proceso, Nombre, Tiempo, Fecha) VALUES('" + idTerminal + "', '" + Proceso + "', '" + Nombre + "', '1,'" + this.ObtenerFechaHora() + ")";
I been used loot of formats and i keep having error, for example:
e.ToString("yyyy-MM-dd H:mm:ss");
e.ToString("yyyy-MM-dd HH:mm:ss");
e.ToString("dd-MM-yyyy H:mm:ss");
e.ToString("yyyy-dd-MMH:mm:ss");
Also with "/" instead of "-"
Any help here?
The problem isn't with the format of the datetime string; the problem is in the SQL text of the INSERT statement, right before the value is appended. For debugging this, you could output the query string and inspect it.
The problem is in the SQL text here:
+ "', '1,'" +
There needs to be a comma between that literal and the next column value. It looks like you just missed a single quote:
+ "', '1','" +
^
A potentially bigger problem is that your code appears to be vulnerable to SQL Injection. Consider what happens when one of the variables you are including into the SQL text includes a single quote, or something even more nefarios ala Little Bobby Tables. http://xkcd.com/327/.
If you want a column value to be the current date and time, you don't need to run a separate query to fetch the value. You could simply reference the function NOW() in your query text. e.g.
+ "', '1', NOW() )";
You excuted twice
//cmd.ExecuteNonQuery();
DateTime e = (DateTime)cmd.ExecuteScalar();
Should be only one time.
Then like #sgeddes said in the comments use parameterized queries, they avoid errors and sql injections.
The approach that you have used is not the best approach to write SQL command. You should use sql parameters in the Query. Your code is vulnerable to SQL Injected and obviously it is not the best approach.
Try using something like this:
string commandText = "UPDATE Sales.Store SET Demographics = #demographics "
+ "WHERE CustomerID = #ID;";
SqlCommand command = new SqlCommand(commandText, connection);
command.Parameters.Add("#ID", SqlDbType.Int);
command.Parameters["#ID"].Value = customerID;

Storing Data in SQLite

Is there a way to store TEXT in SQLite database without SQLite trying to parse it?
Ran into a problem where when you store TEXT that is similar to SQLite query, it tries to parse it for some reason.
Query I use to save TEXT: "insert into tableName (Name, DateCreated, Reminder, Content) values ('name', 'currentDate', 'reminder', 'content')".
Similar text I'm trying to save: "SELECT NAME FROM sqlite_master WHERE TYPE='table' ORDER BY NAME".
When i try to save something like that, it says: Error: SQL logic error or missing database near "table":syntax error
Please note that values (name, currentDate, reminder, content) are not hard coded, they are passed as strings. actual code is like below:
SQLiteCommand command = new SQLiteCommand("insert into " + cateName + " (Name, DateCreated, Reminder, Content) values ('" + noteName + "', '" + currentDate + "', '" + reminder + "', '" + content + "')", connection);
Thanks for any input.
As I suspect, the problem is that you're putting your values directly into the SQL - without even trying to escape them. Don't do that. As well as the problems you're seeing, you've opened yourself up to a SQL injection attack. Use parameterized SQL instead, and specify values for the parameters.
For example:
// It's not clear what cateName is, but I'll assume *that* bit is valid...
string sql = new SQLiteCommand("insert into " + cateName +
" (Name, DateCreated, Reminder, Content) values " +
"(#Name, #DateCreated, #Reminder, #Content)");
using (var command = new SQLiteCommand(sql, connection))
{
command.Parameters.Add("#Name", SQLiteType.Text).Value = noteName;
command.Parameters.Add("#DateCreated", SQLiteType.DateTime).Value = currentDate;
command.Parameters.Add("#Reminder", SQLiteType.Text).Value = reminder;
command.Parameters.Add("#Content", SQLiteType.Text).Value = content;
command.ExecuteNonQuery();
}

Datetime insert in sql shows error when having date as a foreign language

I have made a small application where i save students data. I installed it on my PC and it worked just fine.
I gave it to one of my friend to install it on his system, however his windows is in German language, he installed the software perfectly, but when he was trying to store the data he got the error for date field.
What he explained me on the phone that it was a language error as when i was storing the data on my computer which is in English language, date time appeared like this:
Now when he installed my app on his computer the Date of birth field was in German Language and so he got an error while mssql insert query.
My question is how to force the application to use the Date time in just English language as a System time and not that the client language date time?
I am using sqlServerCe
EDIT
QueryGrid("INSERT INTO students (p_num, p_name, p_fname, p_dob, p_street, p_zip, p_phone, p_email, p_sex, p_comment, p_fax, p_pic, p_regdate, p_idc) VALUES('" + p_num.Text + "', '" + p_name.Text + "', '" + p_fname.Text + "', '" + p_dob.Value + "', '" + p_street.Text + "', '" + p_zip.Text + "', '" + p_pno.Text + "', '" + p_email.Text + "', '" + gender + "', '" + comment_box.Text + "', '" + p_fno.Text + "', '" + p_num.Text + "', '" + DateTime.Now + "', '" + p_idc.Text + "')")
MessageBox.Show("Student successfully added in database.")
Now in above code p_dob.Value is my date value. and when i use it on my computer it converts the above Monday, October 22, 2012 to 10/22/2012 11:31 AM and saves into database, now on my friends system its in German language, so its unable to convert and save.
As I said in mycomment, you should never write a query concatenating string: use queries with parameters.
Example:
string query = "INSERT INTO mytable (p_num, p_date) SELECT #num,#dt";
using (SqlConnection conn = new SqlConnection("....."))
{
conn.Open();
using (SqlCommand cmd = new SqlCommand(query, conn))
{
cmd.Parameters.AddWithValue("num", 1);
cmd.Parameters.AddWithValue("dt", DateTime.Today);
cmd.ExecuteNonQuery();
}
conn.Close();
}
Naturally this is only part of the code, but should give you an idea.
Concatenating strings can lead you to many troubles, not only with dates but with doubles too.
In general: write queries using params to avoid problems with localization (and others).

Categories