Execute Datetime from C# to date in SQL Server 2008 - c#

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

Related

Connecting to Access database

I'm trying to connect to database file "crepeDB.accdb"
When I added it through data connection, and works fine when I drag any table to appear as data grid in any form but when I try to connect to the database to insert data it gives me this error:
An unhandled exception of type 'System.NotImplementedException' occurred in Additional information: The method or operation is not implemented.
The code I'm using is as follows:
System.Data.OleDb.OleDbConnection conn = new System.Data.OleDb.OleDbConnection();
// TODO: Modify the connection string and include any
// additional required properties for your database.
conn.ConnectionString = (#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;");
conn.Open();
string query = "insert into Sales (Sdate,SQuantity) values ('" + dateTimePicker1.Value + "','" + textBox9.Text + "')";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.ExecuteNonQuery();
This is the last thing I need to do in my project, would really appreciate any help.
Do not pass values for your fields concatenating them to form your command, instead use parameters.
int quantity;
if(!Int32.TryParse(textBox9.Text, out quantity))
MessageBox.Show("Invalid number");
else
{
using(OleDbConnection conn = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data source=|DataDirectory|\\crepeDB.accdb;"))
{
conn.Open();
string query = #"insert into Sales (Sdate,SQuantity)
values (#date, #qta)";
OleDbCommand cmd = new OleDbCommand(query, conn);
cmd.Parameters.Add("#date", OleDbType.Date).Value = dateTimePicker1.Value;
cmd.Parameters.Add("#qta", OleDbType.Integer).Value = quantity;
cmd.ExecuteNonQuery();
}
}
This is better because you don't ask someone else to convert your values from a string to the correct datatype. This automatic conversion (in particular with dates) is well know to cause problems when there is some kind of mismatch between the passed string and how the database engine interprets this string
N.B I am assuming the Sdate is a field of type DateTime and SQuantity is a field of type Integer in MS-Access. If not then you can change the OleDbType Int32.TryParse to the correct matching type
It is basically like this . . .
con.Open();
SqlCommand cmd = new SqlCommand(#"insert into tbl_insert values(#name,#email,#add)", con);
cmd.Parameters.AddWithValue("#name", txtname.Text);
cmd.Parameters.AddWithValue("#email", txtemail.Text);
cmd.Parameters.AddWithValue("#add", txtadd.Text);
cmd.ExecuteNonQuery();
con.Close();

MySql Update won't work

Good day! I need help please..
This is my code on c# whenever I execute it nothing happens no error or hint
string myConnection = " datasource=localhost;port=3306;username=root;password=wolf";
string Query = " UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate='" + txtToBeReturned.Text + "' WHERE bikeID='" + txtBikeIdRent.Text + "'";
MySqlConnection myConn = new MySqlConnection(myConnection);
MySqlCommand SelectCommand = new MySqlCommand(Query, myConn);
myConn.Open();
MessageBox.Show("Data Saved");
myConn.Close();
I am not sure why the Upate won't work but when I execute this code on MySql
UPDATE bikerentaldb.tblbikes SET status='Rented',renteddate=NOW(),assignedreturndate=NOW() WHERE bikeID='2';
It works just fine can someone help me?
A command should be executed to do anything. Your code misses the call to SelectCommand.ExecuteNonQuery() line after the open connection. However after fixing this trivial error you could encounter other problems with the values concatenated to form your command text. What if the user types an invalid date? Have you ever heard of Sql Injection hacks?
This is how your code should be written after adding validation to your inputs and parameters to send values to your database
int bikeID = 0;
if(!Int32.TryParse(txtBikeIdRent.Text, out bikeID)
{
MessageBox.Show("Invalid number");
return;
}
DateTime returnDate;
if(!DateTime.TryParse(txtToBeReturned.Text , out returnDate)
{
MessageBox.Show("Invalid date");
return;
}
string myConnection = ".....";
string Query = #"UPDATE bikerentaldb.tblbikes
SET status='Rented', renteddate=NOW(),
assignedreturndate=#date
WHERE bikeID=#id";
using(MySqlConnection myConn = new MySqlConnection(myConnection))
using(MySqlCommand cmd = new MySqlCommand(Query, myConn))
{
myConn.Open();
cmd.Parameters.Add("#date", MySqlDbType.Date).Value = returnDate;
cmd.Parameters.Add("#id", MySqlDbType.Int32).Value = bikeID;
int rowUpdated = cmd.ExecuteNonQuery();
if(rowUpdated > 0)
MessageBox.Show("Record updated");
else
MessageBox.Show("No record match");
}

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!

How to convert C# DateTime to MySQL timestamp table column

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();
}

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