How to convert C# DateTime to MySQL timestamp table column - c#

I'm trying to update a table element of type timestamp called dtprint with the current time (the original value is NULL). The code that I am using is as follows:
MySqlConnection con = new MySqlConnection("Connection_String");
con.Open();
MySqlCommand _cmd = con.CreateCommand();
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
_cmd.CommandText = "UPDATE requests SET dtprint = " + dt + " WHERE idPerson = " + _personID[index];
_cmd.ExecuteNonQuery();
con.Close();
The exception I keep getting is: Additional information: 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 '14:03:23 WHERE idPerson = 45' at line 1.
The only thing I can think of is that the Database isn't recognizing the time as a timestamp, any help is greatly appreciated.

Since dt is a string and your dtprint is timestamp, you need to use single quotes when you try to insert it. Like;
"UPDATE requests SET dtprint = '" + dt + "' WHERE
But don't use this way.
You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
Also use using statement to dispose your database connections and objects.
using(MySqlConnection con = new MySqlConnection(ConnectionString))
using(MySqlCommand _cmd = con.CreateCommand())
{
string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
_cmd.CommandText = #"UPDATE requests SET dtprint = #dtprint
WHERE idPerson = #id";
_cmd.Parameters.Add("#dtprint", MySqlType.TimeStamp).Value = dt;
_cmd.Parameters.Add("#id", MySqlType.Int).Value = _personID[index];
con.Open();
_cmd.ExecuteNonQuery();
}

Related

C# Access Db update query not working

I am trying to update an access table with the code noted below. however, the update does not execute. It doesn't give me any errors but it doesn't update the database. Any suggestions?
string Const = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=F:\\Db\\test.accdb";
OleDbCommand Cmd;
OleDbConnection con22 = new OleDbConnection(Const );
con22.Open();
string sql = "UPDATE CostT SET tFormSent='" + Selection1.Text + "',TName='" + UserName.Text + "',FormDate='" + FormDate.Text + "',where ReqNum=" + ReqNum.Text;
cmd = new OleDbCommand(sql, con22);
cmd.ExecuteNonQuery();
con22.Close();
MessageBox.Show("Form has been Updated");
Try changing the query
to
string sql = "UPDATE CostT SET tFormSent = #selection1,TName = #UserName,FormDate = #FormDate where ReqNum = #ReqNum";
cmd = new OleDbCommand(sql, con22);
cmd.Parameters.Add("#selection1", Selection1.Text);
cmd.Parameters.Add("#UserName", UserName.Text);
cmd.Parameters.Add("#FromDate", FromDate.Text);
cmd.Parameters.Add("#ReqNum", ReqNum.Text);
cmd.ExecuteNonQuery();
con22.Close();
Your query has a syntax error: you have a comma before your WHERE clause that does not belong there.
But more important: Your code is open to SQL injection! Please don't insert user input directly into your query, but use parameterized queries instead!

Print My Search Results From SQL Server on label

I'm just trying to print the sum of my search on a label in form.
Story is I have 2 textboxes that will give me 2 date and searching in my database, and printing the answer of sum cost between that 2 date.
My code is :
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=localhost;Initial Catalog=SuperCalc;Integrated Security=True");
SqlCommand com = new SqlCommand();
if (con.State == ConnectionState.Closed)
{
con.Open();
com = new SqlCommand("select sum (Cost) as JameKol From TBL_Cost Where CostDate between '" + textBox1.Text + "' and '" + textBox2.Text + "' ", con);
label5.Text = com();
con.Close();
MessageBox.Show("Search is done", "Done");
}
}
com can't use as a method, so, how can I do this?
Just use ExecuteScalar which is exactly what this for. It gets first column of the first row which fits SUM function.
label5.Text = com.ExecuteScalar().ToString();
But more important, you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.
And use using statement to dispose your connection and command automatically instead of calling Close method manually.
By the way, looks like your CostDate column is character typed. Don't do it. This is a bad habit to kick. You should never keep your DateTime values as a character. Change it to datetime or better datetime2 type and pass your DateTime values directly to your parameterized query. That's why I used DateTime.Parse to parse your Text values. If it can't parse them, you can use ParseExact as well.
string conString = "Data Source=localhost;Initial Catalog=SuperCalc;Integrated Security=True";
using(var con = new SqlConnection(conString))
using(var com = con.CreateCommand())
{
com.CommandText = #"select sum (Cost) as JameKol From TBL_Cost
Where CostDate between #date1 and #date2";
com.Parameters.Add("#date1", SqlDbType.DateTime2).Value = DateTime.Parse(textBox1.Text);
com.Parameters.Add("#date2", SqlDbType.DateTime2).Value = DateTime.Parse(textBox2.Text);
con.Open();
label5.Text = com.ExecuteScalar().ToString();
}

Execute Datetime from C# to date in SQL Server 2008

I'm new in programming and want you to help me.
I have field of type (date) and when I insert data to database from my website in visual studio 2010 with C#, it Shows me an error during execution.
Can anyone help me?
Thank you
Code behind
string InsMus = "Insert into StoreMus (MusNo,MusDate)" +
"Values (" + Convert.ToInt16(txtMusNo.Text) + ",'" + DateTime.Parse(txtMusDate.Text) + "')";
cmd = new SqlCommand(InsMus , con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Don't use string concanation to prevent sql injection. I'm sure that it will also fix this issue.
string InsMus = #"Insert into StoreMus (MusNo,MusDate)
Values (#MusNo, #MusDate);";
using(var con = new SqlConnection("Connection String..."))
using(var cmd = new SqlCommand(InsMus, con))
{
cmd.Parameters.Add("#MusNo", SqlDbType.SmallInt).Value = short.Parse(txtMusNo.Text);
cmd.Parameters.Add("#MusDate", SqlDbType.Date).Value = DateTime.Parse(txtMusDate.Text);
con.Open();
int inserted = cmd.ExecuteNonQuery();
}
Note that i've used the using-statement to ensure that the connection gets disposed/closed.
You could also use DateTime.TryParse instead of DateTime.Parse to prevent an exception that happens when the format of the date is invalid:
DateTime musDate;
if(!DateTime.TryParse(txtMusDate.Text, out musDate))
{
MessageBox.Show("Please enter a valid mus-date.");
return;
}
// here you can use musDate

SQL statement with datetimepicker

This should hopefully be a simple one. When using a date time picker in a windows form, I want an SQL statement to be carried out, like so:
string sql = "SELECT * FROM Jobs WHERE JobDate = '" + dtpJobDate.Text + "'";
Unfortunately, this doesn't actually provide any results because the JobDate field is stored as a DateTime value. I'd like to be able to search for all records that are on this date, no matter what the time stored may be, any help?
New query:
SqlDataAdapter da2 = new SqlDataAdapter();
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Jobs WHERE JobDate >= #p_StartDate AND JobDate < #p_EndDate";
cmd.Parameters.Add ("#p_StartDate", SqlDbType.DateTime).Value = dtpJobDate.Value.Date;
cmd.Parameters.Add ("#p_EndDate", SqlDbType.DateTime).Value = dtpJobDate.Value.Date.AddDays(1);
cmd.Connection = conn;
da2.SelectCommand = cmd;
da2.Fill(dt);
dgvJobDiary.DataSource = dt;
Huge thanks for all the help!
Just one answer: use parametrized queries.
This is for different reasons:
security (no risk of SQL
Injection
no longer those problems for which you're opening a topic
performance.
Thus, write your statement like this:
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "SELECT * FROM Jobs WHERE JobDate = #p_Date"
cmd.Parameters.Add ("#p_Date", SqlDbType.DateTime).Value = dtpJobDate.Value;
If you want to ignore the time, then I think the best bet is to do a range search, if the time is stored in the DB, that is.
Something like this (just the SQL query):
SELECT * FROM Jobs WHERE JobDate >= #p_StartDate AND JobDate < #p_EndDate
StartDate would then be dtpJobDate.Value.Date, and EndDate would be dtpJobDate.Value.Date.AddDays(1)
If the Time is not stored in the DB, then you can do this:
SELECT * FROM Jobs WHERE JobDate = #p_Date
where the search argument should be dtpJobDate.Value.Date
Try dtpJobDate.Value.
Other than the SQL injection stuff in other answers, you can use something like this:
dtpJobDate.Value.ToString("yyyyMMdd HH:mm:ss");
But probably you won't find anything with exact time match, so you can change your query for something like
string sql = "SELECT * FROM Jobs WHERE JobDate BETWEEN '" + dtpJobDateStart.Value.ToString("yyyyMMdd HH:mm:ss") + "' AND '" + + dtpJobDateEnd.Value.ToString("yyyyMMdd HH:mm:ss") + " + "'";
First of all - you have left a door open for SQL injection in your example.
Other than that - to answer your question, you'll have to drop the times off of the JobDate column to get the match done. Try something like this (SQL Injection code left in example for comparison)...
string sql = "SELECT * FROM Jobs WHERE CAST(CONVERT(CHAR(8), JobDate, 112) AS DATETIME) = '" + dtpJobDate.Text + "'";
If you were to parameterize your query - you could do it something like this...
using (var conn = new SqlConnection(myConnectionString))
using (var cmd = new SqlCommand("SELECT * FROM Jobs WHERE JobDate = #JobDate", conn))
{
cmd.Parameters.Add(new SqlParameter("#JobDate", dtpJobDate.Value));
conn.Open();
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
// your code here to deal with the records...
}
}
}

Conversion failed when converting datetime from character string

when i compile the following code , "Conversion failed when converting datetime from character string" exception raises , what is wrong with that ?
code :
DateTime after3Dyas = DateTime.Now.AddDays(3);
try
{
Con.Open();
SqlCommand Command = Con.CreateCommand();
Command.CommandText = "Select * from Forcast Where City='" + city + "' And Date between '" + DateTime.Now.Date + "' and '" + after3Dyas.Date + "'";
SqlDataReader thisReader = Command.ExecuteReader();
int i=0;
while (thisReader.Read())
{
//do something
i++;
}
thisReader.Close();
The database is trying to convert the value from whatever DateTime.ToString is giving you... do you really want to trust that .NET on your calling machine and SQL Server use exactly the same format? That sounds brittle to me.
Avoid this by not putting the value into the SQL directly in the first place - use a parameterized query. This not only avoids conversion issues, but also (equally importantly) avoids SQL injection attacks.
Sample code:
DateTime start = DateTime.Now;
DateTime end = start.AddDays(3);
string sql = #"
SELECT * FROM Forecast
WHERE City = #City AND Date BETWEEN #StartDate AND #EndDate";
// Don't forget to close this somewhere. Why not create a new connection
// and dispose it?
Con.Open();
using (SqlCommand command = new SqlCommand(sql, Con))
{
command.Parameters.Add("#City", SqlDbType.NVarChar).Value = city;
command.Parameters.Add("#StartDate", SqlDbType.DateTime).Value = start;
command.Parameters.Add("#EndDate", SqlDbType.DateTime).Value = end;
using (SqlDataReader reader = command.ExecuteReader())
{
int i = 0;
while (reader.Read())
{
//do something
i++;
}
}
}
You should use parametrized query.
If you don't want to use parametrized query, use CONVERT function:
"Select * from Forcast Where City='" + city + "' And Date = CONVERT(DATETIME,'" + DateTime.Now.ToString("yyyy-MM-dd") + "',120)
CONVERT(Datetime,'2009-12-25',120) converts varchar type to datetime type with specified format. It will also help with sql injection, but parameters are better solution.
Try the format below instead :
DateTime.Now.ToString("yyyy-MM-dd")
But I strongly advice you to use parameters, because of security issues :
Command.CommandText =
"Select * from Forcast Where City=#City And Date between #StartDate and #EndDate";
SqlParameter city = new SqlParameter("#City", SqlDbType.VarChar, 10);
city.Value = yourCityValue;
Command.Parameters.Add(city);
SqlParameter startDate = new SqlParameter("#StartDate", SqlDbType.DateTime);
startDate.Value = yourStartDate;
Command.Parameters.Add(startDate);
SqlParameter endDate = new SqlParameter("#EndDate", SqlDbType.DateTime);
endDate.Value = yourEndDate;
Command.Parameters.Add(endDate);
You should use parameterised queries whenever possible. There are several reasons such as:
You will avoid sql injection attacks.
Execution plans for parameterised queries will be cached by sql server so you will get better performance when executing the same query with different parameter values.
You will avoid need to escape string parameters.
See the following article for more details: http://www.codeproject.com/KB/database/SqlInjectionAttacks.aspx

Categories

Resources