I am trying to insert into a SQL Server database using a C# application.
In C# I am using datetime.now to get the current datetime:
order.PendingDateTime = DateTime.Now;
This gives me 25/07/2014 11:30:17.
In the SQL Server table the datatype is datetime. Which holds the data as 2014-07-23 14:54:01.607 for example.
However running the value 25/07/2014 11:30:17 using a normal insert script it inserts into the SQL Server table fine but displays in the table as 2014-07-25 11:30:17. (This is ok)
However when I use SqlConnection
using (con)
{
con.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con;
cmd.CommandText = #sql;
cmd.ExecuteScalar();
}
}
It fails, it says
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value. The statement has been terminated.
I think this is because Visual Studio 2010 and SQL Server uses a different datetime format to each other.
How do I fix this?
Current Code:
string sql = "INSERT INTO Order ([LedgerNumber], [OrderNumber], [OrderDate], [PendingDateTime], [EmailAddress]) VALUES (1, '" + rec.OrderNumber + "', CONVERT(datetime, '" + rec.OrderDate + "', 120), CONVERT(datetime, '" + rec.PendingDateTime + "', 120), '" + rec.EmailAddress + "')";
try
{
SqlConnection con2 = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OrderContext"].ConnectionString);
using (con2)
{con2.Open();
using (SqlCommand cmd = new SqlCommand())
{
cmd.Connection = con2;
cmd.CommandText = #sql;
cmd.Parameters.AddWithValue("rec.PendingDateTime", DateTime.Now);
cmd.Parameters.AddWithValue("rec.OrderDate", rec.OrderDate);
cmd.ExecuteScalar();
}
Always use sql-parameters instead of string-concatenation. It prevents you from such issues and - more important - from sql-injection:
string sql = #"INSERT INTO Order ([LedgerNumber], [OrderNumber], [OrderDate], [PendingDateTime], [EmailAddress])
VALUES (1, #OrderNumber, #OrderDate, #PendingDateTime, #EmailAddress)";
using (var con = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["OrderContext"].ConnectionString))
using (SqlCommand cmd = new SqlCommand(sql, con))
{
cmd.Parameters.AddWithValue("#OrderNumber", rec.OrderNumber);
cmd.Parameters.AddWithValue("#OrderDate", rec.OrderDate);
cmd.Parameters.AddWithValue("#PendingDateTime", rec.PendingDateTime);
cmd.Parameters.AddWithValue("#EmailAddress", rec.EmailAddress);
con.Open();
cmd.ExecuteNonQuery();
}
You: "if I wasn't using datetime.now and get a datetime from a value entered by user. Say '24/07/2014 10:30' how do I use the AddWithValue to achieve this?"
You have to parse the input to DateTime first. Therefore use DateTime.Parse or DateTime.TryParse, DateTime.ParseExact or DateTime.TryParseExact. The TryParse-methods enable you to check if the input is a valid DateTime.
For example:
DateTime pendingDateTime;
if(!DateTime.TryParse(TxtPendingDateTime.Text, out pendingDateTime))
{
MessageBox.Show("Please enter a valid Pending-Date in the format: yourformat");
return;
}
// here you can go on with the code above
Related
I want to insert C# winform values to Mysql
there are 3 columns
name,id are TextBox text and gender is ComboBox value
but there is error and error messsage said: MySql.Data.MySqlClient.MySqlException: '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 '',')' at line 1'
what code should i fix?
using (MySqlConnection conn2 = new MySqlConnection(strconn))
{
conn2.Open();
string query = "INSERT INTO student1(name,id,gender) values ('" + name3.Text + "'," + id3.Text + "'," + gender3.SelectedValue+"');";
MySqlCommand cmd = new MySqlCommand(query, conn2);
cmd.ExecuteNonQuery();
}
You're missing a single quote in the connecting string literal between name3.Text and id3.Text and again between id3.Text and gender3.SelectedValue
But it shouldn't matter. If you're concatenating user-supplied strings like this it's only a matter of time until your system is breached. There's a better way that avoids this risk, makes it easier to get your SQL statements correct, and runs faster.
//This could be marked const!
string query = "INSERT INTO student1(name,id,gender) values (#name, #id, #gender);";
using (var conn2 = new MySqlConnection(strconn))
using (var cmd = new MySqlCommand(query, conn2))
{
//I have to guess, but you can find exact column types/lengths from your db
//Do not use AddWithValue()!
// MySql is less at risk for the AddWithValue() performance issues
// than Sql Server but the risk isn't completely eliminated.
cmd.Parameters.Add("#name", MySqlDbType.VarChar, 30).Value = name3.Text;
cmd.Parameters.Add("#id", MySqlDbType.VarChar, 50).Value = id3.Text;
cmd.Parameters.Add("#gender", MySqlDbType.VarChar, 5).Value = gender3.SelectedValue;
conn2.Open();
cmd.ExecuteNonQuery();
}
using (MySqlConnection conn2 = new MySqlConnection(strconn))
{
String query = "INSERT INTO student1(name,id,gender) values (#name,#id,#gender)";
MySqlCommand = new MySqlCommand(query, conn2);
command.Parameters.AddWithValue("#name", name3.Text);
command.Parameters.AddWithValue("#id", id3.Text);
command.Parameters.AddWithValue("#gender", gender3.SelectedValue.ToString());
command.ExecuteNonQuery();
}
use need use parameters
how to insert the current time using ado.net sql command. getting error saying The "conversion of a varchar data type to a datetime data type resulted in an out-of-range value."
code
DateTime NowTime = DateTime.Now;
string usecase = "manhole";
SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString);
con.Open();
SqlCommand cmdInsert = new SqlCommand("insert into sms values('" + usecase + "','" + smsbody + "','" + NowTime + "')", con);
try
{
cmdInsert.ExecuteNonQuery();
}
columns
updtd_date is datetime
query
INSERT INTO sms (usecase, sms, updtd_date)
VALUES ('manhole','level is low at : 22/01/2018 15:56:20','22/01/2018 16:18:28');
You should use a parametized query instead of concatenating strings, what you are doing is asking for an SQL Injection. Also, you should dispose commands and connections after use them in order to release memory.
using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["constr"].ConnectionString))
{
using (var command = new SqlCommand("insert into sms (col1) values(#col1"))
{
command.Parameters.AddWithValue("#col1", DateTime.Now);
con.Open();
command.ExecuteNonQuery();
}
}
Use The Function GETDATE() To Get the System Date and Time.
Change NowTime
"insert into sms values('" + usecase + "','" + smsbody + "','" + NowTime + "')"
To This
"insert into sms values('" + usecase + "','" + smsbody + "',GETDATE())"
Executing the SQL Statements Like this Can Cause SQL Injection, So I Recommend using Parameter may Be Something Like this
using (SqlConnection con = new SqlConnection(dc.Con)) {
using (SqlCommand cmd = new SqlCommand("insert into sms values(#usecase,#smsbody,GETDATE())", con)) {
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#usecase", SqlDbType.VarChar).Value = usecase;
cmd.Parameters.Add("#smsbody", SqlDbType.VarChar).Value = smsbody;
con.Open();
cmd.ExecuteNonQuery();
}
}
I think you need to be specific with the date format in SQL if you inserting a date if you not using paramater:
string nowDate = DateTime.Now.ToString("dd MMM yyy HH:mm:ss");
string sql = "insert into #dateT values('"+nowDate+"')";
This results to this in my pc
insert into #dateT values('22 Jan 2018 13:27:04');
I am a beginner in asp.net. I am using a query :
string num = ("SELECT count(*) from booking WHERE date='" + dt + "' AND start_time='" + stime + "' AND end_time='" + etime + "' AND lid='" + hostloc + "'");
SqlCommand cmd = new SqlCommand(num, con);
con.Open();
int count = (int)cmd.ExecuteScalar();
con.Close();
Sometimes when i submit my web form it gives me an SqlException :
"The conversion of a char data type to a datetime data type resulted
in an out-of-range datetime value."
This does not happen always!!
Please, any help is appreciated..
Thank You in advance
string num = "SELECT count(*) from booking WHERE date=#dt AND start_time=#stime AND end_time=#etime AND lid=#hostloc";
using(SqlCommand cmd = new SqlCommand(num, con))
{
cmd.Parameters.AddWithValue("dt", dt);
// etc for all params
con.Open();
int count = (int)cmd.ExecuteScalar();
}
Note this assumes dt is a DateTime etc.
This solves multiple problems, including formatting, localisation and SQL injection.
First of all use parameterized queries for your SQL calls or you might get SQL injected soon enough.
Also you need to convert dt to datetime before you send the variable to the SQL Server in order to avoid such errors, like Convert.ToDatetime(dt).
I am doing a web development in ASP.net with C#.
I am trying to insert some values into the database and get a last inserted id.
This is my code:
int userno2 = Convert.ToInt32(Session["user_id"].ToString());
con = new SqlConnection(ConfigurationManager.ConnectionStrings["default"].ConnectionString);
createorder = new SqlDataAdapter("INSERT INTO order (user_id, date) VALUES ('" + userno2 + "', '12-12-2013');select SCOPE_IDENTITY();", con);
order = new DataSet();
createorder.Fill(order, "or_det");
Int32 ord_id = Convert.ToInt32(order.Tables[0].Rows[0]["order_id"].ToString());
When I try to execute the program it gives an error
Incorrect syntax near the keyword 'order'.
Can anyone please help me to fix this error?
order is a reserved word in SQL. If you are using SQL Server, use square brackets to escape it []:
createorder = new SqlDataAdapter("INSERT INTO [order] (user_id, date) VALUES ('" + userno2 + "', '12-12-2013');select SCOPE_IDENTITY();", con);
ORDER is a reserved keyword in T-SQL.
Either don't call your table ORDER, or then you need to "escape" the name with square brackets:
INSERT INTO [order](user_id, date) VALUES ('" + userno2 + "', '12-12-2013');select SCOPE_IDENTITY();", con);
Also: do NOT string together your SQL statement like this! This is highly vulnerable to SQL injection attacks!
Use a parametrized query instead!
INSERT INTO [order](user_id, date) VALUES (#UserId, #Date);
SELECT SCOPE_IDENTITY();
To just insert the row and retrieve the newly inserted ID, I'd personally use a simple SqlCommand and not go the way of using SqlDataAdapter:
string insertStmt = "INSERT INTO [order](user_id, date) VALUES (#UserId, #Date); SELECT SCOPE_IDENTITY();";
using (SqlCommand insertCmd = new SqlCommand(insertStmt, yourSqlConnection))
{
insertCmd.Parameters.Add("#UserID", SqlDbType.Int).Value = xy;
insertCmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Now;
yourSqlConnection.Open();
int newID = (int)insertCmd.ExecuteScalar();
yourSqlConnection.Close();
}
Other than marc_s answer do not use dataset to fetch a single value instead use ExecuteScalar method .
string sql =
"INSERT INTO [order] (user_id, date) VALUES (#user_id, #date); "
+ "SELECT CAST(scope_identity() AS int)";
using (SqlConnection conn = new SqlConnection(connString))
{
using (SqlCommand cmd = new SqlCommand(sql , cmd))
{
cmd.Parameters.Add("#user_id", SqlDbType.VarChar);
cmd.Parameters.Add("#date", SqlDbType.DateTime).Value = DateTime.Now;
try
{
conn.Open();
ord_id = (Int32)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
I'm inserting a datetime field to sql server. From my local computer it works just fine. example: the datetime field in sql server is : "2013-07-31 08:00:00.000", but when I run the application form the server it switches the day and month and insert it like this:
"2013-07-31 15:15:00.000".
My relevant page loads some entries from the sql server depending on today's date.
Like this:
public List<act_event> return_event_list(DateTime date) //return all events for spesific date
{
List<act_event> event_list = new List<act_event>();
String date_sql = date.ToString("yyyy-MM-dd");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where '" + date_sql + "'>=(CAST(e_start as DATE)) and '" + date_sql + "'<=(CAST(e_end as DATE))"))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
act_event a_event = new act_event();
a_event.e_num = Convert.ToInt32(rdr["e_num"]);
a_event.name = rdr["e_name"].ToString();
a_event.start = Convert.ToDateTime(rdr["e_start"]);
a_event.end = Convert.ToDateTime(rdr["e_end"]);
a_event.description = rdr["e_description"].ToString();
a_event.address = rdr["e_address"].ToString();
event_list.Add(a_event);
}
}
}
}
return event_list;
}
This is how I insert the datetime fields:
public void add_event(act_event add_avent)
{
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "insert into act_events values(#e_name, #e_start, #e_end, #e_description, #e_address)"))
{
cmd.Parameters.AddWithValue("#e_name", add_avent.name);
SqlParameter param2 = new SqlParameter("#e_start", SqlDbType.DateTime);
param2.Value = add_avent.start;
cmd.Parameters.Add(param2);
SqlParameter param3 = new SqlParameter("#e_end", SqlDbType.DateTime);
param3.Value = add_avent.end;
cmd.Parameters.Add(param3);
//cmd.Parameters.Add(new SqlParameter("#e_start", SqlDbType.DateTime));
//cmd.Parameters["#e_start"].Value = DateTime.Parse(add_avent.start.ToString());
//cmd.Parameters.Add(new SqlParameter("#e_end", SqlDbType.DateTime));
//cmd.Parameters["#e_end"].Value = DateTime.Parse(add_avent.end.ToString());
cmd.Parameters.AddWithValue("#e_description", add_avent.description);
cmd.Parameters.AddWithValue("#e_address", add_avent.address);
cmd.ExecuteNonQuery();
}
//using (SqlCommand cmd2=create_command
}
}
I tried changing the select command, adding this:
using (SqlCommand cmd = create_command(con, "select * from act_events where ( '" + date_sql + "'>=(CAST(e_start as DATE)) and '" + date_sql + "'<=(CAST(e_end as DATE)) ) or ( '" + date_sql2 + "'>=(CAST(e_start as DATE)) and '" + date_sql2 + "'<=(CAST(e_end as DATE)) ) "))
but for some of the dates it gives me an error:
Conversion failed when converting date and/or time from character
string.
What should I do?
EDIT:
I tried to run the query from the sql studio itself like this:
select * from act_events where ( '2013-08-03'>=(CAST(e_start as DATE)) and '2013-08-03'<=(CAST(e_end as DATE)) ) or ( '2013-03-08'>=(CAST(e_start as DATE)) and '2013-03-08'<=(CAST(e_end as DATE)) )
it gives me:
But if I run it like this: (different date)
select * from act_events where ( '2013-07-30'>=(CAST(e_start as DATE)) and '2013-07-30'<=(CAST(e_end as DATE)) ) or ( '2013-30-07'>=(CAST(e_start as DATE)) and '2013-30-07'<=(CAST(e_end as DATE)) )
it gives me this error:
EDIT2:
After James suggestion I made a parameterized query like this:
String date_sql = date.ToString("yyyy-MM-dd");
String date_sql2 = date.ToString("yyyy-dd-MM");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where #date1>=(CAST(e_start as DATE)) and #date2<=(CAST(e_end as DATE))"))
{
cmd.Parameters.AddWithValue("#date1", date_sql);
cmd.Parameters.AddWithValue("#date2", date_sql);
cmd.Parameters.AddWithValue("#date3", date_sql2);
cmd.Parameters.AddWithValue("#date4", date_sql2);
which still won't load the correct entries from the sql server
Then I tried this query:
String date_sql = date.ToString("yyyy-MM-dd");
String date_sql2 = date.ToString("yyyy-dd-MM");
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con, "select * from act_events where ( #date1>=(CAST(e_start as DATE)) and #date2<=(CAST(e_end as DATE)) ) or ( #date3>=(CAST(e_start as DATE)) and #date4<=(CAST(e_end as DATE)) )"))
{
cmd.Parameters.AddWithValue("#date1", date_sql);
cmd.Parameters.AddWithValue("#date2", date_sql);
cmd.Parameters.AddWithValue("#date3", date_sql2);
cmd.Parameters.AddWithValue("#date4", date_sql2);
And again it just give me:
Conversion failed when converting date and/or time from character string.
It's never ever really a good idea to try pass date/time's to SQL as string from the client unless you are absolutely certain of the server locale.
Switching to a parameterized query should resolve your issue.
The problems you encounter are due to string to date conversions in one point or another, both on the client and the server's side
You don't need to do any conversionf to string or date if you use a parameterized query and you pass DateTime values, provided of course that the type of your table's fields is also a date type.
The following code makes no conversions at all:
DateTime date1=DateTime.Today.AddMonths(-1);
DateTime date2=DateTime.Today.AddMonths(1);
using (SqlConnection con = connect("igroup20_test2ConnectionString"))
{
using (SqlCommand cmd = create_command(con,
"select * from act_events where " +
" (#date1>=e_start and #date1 <= e_end) " +
" or (#date2>= e_start and #date2 <= e_end) "))
{
cmd.Parameters.AddWithValue("#date1", date1);
cmd.Parameters.AddWithValue("#date2", date2);
You don't need to specify the same date multiple times. If this query doesn't work it's either because the e_start and e_end fields are text fields or the WHERE clause is not what you expected.
You should also check whether #date2 is used correctly. Your query seems to look for records that cover #date1 or don't cover #date2. Is this correct?