How to pass convert expression in parameter using c#? - c#

I had an adhoc insert statement created in c# code using string builder.
var str = new StringBuilder(string.Empty);
str.Append(" INSERT INTO Table_01 ( ID,");
str.Append("Comment,");
str.Append("DateTimeStamp,");
str.Append(" ) VALUES( ");
str.Append("'" + Guid.NewGuid() + "',");
str.Append("'" + CaseComment + "',");
str.Append("CONVERT(DATETIME, '" + DateTime.Now.Year + "/" + DateTime.Now.Month + "/" + DateTime.Now.Day + "',120)");
I have converted this code to SqlParameter:-
var str = INSERT INTO Table_01(ID,Comment,DateTimeStamp)
VALUES(#ID,#Comment,#DateTimeStamp)
using (var cmd = new SqlCommand(str, con))
{
cmd.Parameters.Add(new SqlParameter("#ID", Guid.NewGuid()));
cmd.Parameters.Add(new SqlParameter("#Comment", CaseComment));
cmd.Parameters.Add(new SqlParameter("#DateTimeStamp", ?????));
cmd.ExecuteNonQuery();
}
Before passing DateTime, I have to make sure that format is equal to "convert(varchar, getdate(), 120) -- 2016-10-23 06:10:55(24h)" as in TSQL.
How will i pass #datetime parameter using TSQL Convert expression?

You can use Convert class. Try something like this,
cmd.Parameters.Add(new SqlParameter("#DateTimeStamp", Convert.ToDateTime(DateTime.Now)));
or
cmdItemSearch.Parameters.Add(new SqlParameter("#EndDate", SqlDbType.DateTime));
cmdItemSearch.Parameters["#EndDate"].Value = DateTime.Now;

Why not using String Format for DateTime ?

Assuming that the database column is actually a DateTime and not varchar you don't need to convert on insert if using a parameter. Databases don't save dates as strings, but as offsets, and the only reason you had to convert it when using your inline SQL was because you had to make sure the DB recognized the string as a DateTime so it could internally convert it back correctly. This is avoided using parameters.
(In other words, just insert DateTime.Now, don't rip it apart into a string)

Honestly, whenever I need to insert the current date/time stamp to a table, I like to use the server date as opposed to the client date. If the app is running on the same box as SQL server then it doesn't matter, but if the app is running on a different box then it's better to have consistent dates from the same timezone. So I would remove the datetime parameter altogether and use the SQL date function GetDate() as follow:
var str = INSERT INTO Table_01(ID,Comment,DateTimeStamp)
VALUES(#ID,#Comment,GetDate())
using (var cmd = new SqlCommand(str, con))
{
cmd.Parameters.Add(new SqlParameter("#ID", Guid.NewGuid()));
cmd.Parameters.Add(new SqlParameter("#Comment", CaseComment));
cmd.ExecuteNonQuery();
}

Related

insert datetime value gives error "Incorrect syntax near 12"

DateTime myDateTime = Convert.ToDateTime(rd2[0].ToString())
values = myDateTime.ToString("yyyy-MM-dd HH:mm:ss") + " , " + rd2[1].ToString()+ " , " + rd2[2].ToString()+ " , " + rd2[3].ToString()+ " , " + rd2[4].ToString()+ " , " + rd2[5].ToString() ;
i am trying to insert date 2016-04-22 12:58:11 in sql server table of datatype datetime but it gives error "Incorrect syntax near 12"
The string you end up with is similar to this:
2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00,2016-04-22 00:00:00
Inserting that into a SQL statement is invalid. You need to wrap each date in single quotes so that you have:
'2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00','2016-04-22 00:00:00'
Either way this makes your life difficult and makes your code subject to sql injection and insecure. Consider using parameters like this.
string exampleSQL = "SELECT * from mydatetable where dateOne = #date1 and dateTwo = #date2";
SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(sql, connection);
command.Parameters.Add("#date1", SqlDbType.DateTime).Value = myDateTime;
command.Parameters.Add("#date2", SqlDbType.DateTime).Value = rd2[1];
This way you dont need to worry about formatting. The system automatically will replace the #date1 and #date2 with the values you specified and it will deal with adding the nescessary structure of the SQL without you having to worry about it.
I strongly suggest using "parametrizing your sql queries"...For example, you can check it out here:
http://www.dreamincode.net/forums/topic/268104-the-right-way-to-query-a-database-parameterizing-your-sql-queries/
Cheers!

"Out-of-range value" error when converting a varchar to datetime

I have this code
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
The problem is whenever it is running in server it is giving error. In Local host or in SQL server management it is working fine.
What the heck is it not working whenever it is in the web
The error is The conversion of a varchar data type to a datetime data
type resulted in an out-of-range value. The statement has been
terminated.
Never concatenate string to form SQL queries, always use parameterized query. For your code you can use SqlParameter, with your command. There instead of Converting DateTime to string and then casting it back DateTime in INSERT query , simply add the value of DateTime object in parameter. This will not only save you from Sql Injection but also resolves issues like the one you are having.
Something like:
using(SqlConnection conn = new SqlConnection("Connectionstring"))
using (SqlCommand cmd = new SqlCommand())
{
string sql = "insert into Usertable ";
sql += "values(#mVendid, #usrname, #usrpass, #datecreation, #createdby)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#mVendid", mVendid);
cmd.Parameters.AddWithValue("#usrname", username);
cmd.Parameters.AddWithValue("#usrpass", userpass);
cmd.Parameters.AddWithValue("#datecreation", Convert.ToDateTime(datecreation));
cmd.Parameters.AddWithValue("#createdby", createdby);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
if datecreation is coming from a DateTime object then add that directly, otherwise you can parse it to DateTime object and let SQL server handle the rest for you.
The problem is that probably you server has different language settings that your machine.
To make sure that converting is working you Convert function. Full tutorial is here: http://www.sqlusa.com/bestpractices/datetimeconversion/
BTW constructing queries like concatenate string is very dangerous way. Instead of this use SqlParamerts. Moreover advantage using this approach is that .NET will do conversion for you.
First of all user parameters (better, clearer and safer!). Second this error happens due to format issues.
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string date = DateTime.Parse(datecreation);
string sql = "insert into Usertable values(#mvendid, #username, #usrpass, #date, #createdby)";
var con = new SqlConnection(""); // your connection string
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#mvendid", mVendid);
...
cmd.Parameters.AddWithValue("#date", date);
First of all its really a bad query and quite hacky, you shouldn't be writing query like this
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
*Always use Paramaterised Queries *
Error might be there because you are converting some text to datetime. Possible reasons Datetime not well formed
Dateimte doesn't matches to your server datetime
Try to print out the exact value what its creating
cast('" +
datecreation + "'as DATETIME)
Check the time zone of the server. Likely that it is a different time zone to your local machine. You can avoid the issue by using parameters.
string sql = #"
INSERT INTO Usertable
VALUES (#Parameter1, #Parameter2, #Parameter3, #Parameter4, #Parameter5)";
(using SqlCommand command = new SqlCommand(sql, myConnection))
{
command.Parameters.AddWithValue("#Parameter1", mVendid);
command.Parameters.AddWithValue("#Parameter2", usrname);
command.Parameters.AddWithValue("#Parameter3", usrpass);
command.Parameters.AddWithValue("#Parameter4", todaydate);
command.Parameters.AddWithValue("#Parameter5", createdBy);
command.ExecuteNonQuery();
}

Insert datetime from C# into SQL Server database

when I try to insert datetime value into a SQL Server database I get this error:
Conversion failed when converting date and/or time from character string
Code:
connection.Open();
SqlCommand command = new SqlCommand("insert into table values(#time)", connection);
command.Parameters.AddWithValue("#time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
Table table has 1 datetime column called time.
Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:
public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
{
int id = getMaxID() + 1;
connection.Open();
SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','#cas','" + nazev + "','" + dotaz + "')", connection);
command.Parameters.AddWithValue("#cas", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
}
The actual problem here is that you're writing the parameter inside quotes:
... ,'0','#cas',' ...
^ ^
This will not use #cas as a parameter, you're actually trying to insert the string "#cas" into that column, not the contents of the parameter #cas.
Remove the quotes and that part should work.
Additionally, don't use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the "id", "uzivatel", "nazev", and "dotav" parameters you're using (method parameters that is).
Looks like you need:
insert into table values(#time)
Without the single character quote.
Try System.Data.SqlTypes.SqlDateTime Also when storing dates please consider storing them as UTC to prevent confusion.

how to insert a datepicker datetime value into sql database

My SQL Server 2008 database has a table with a column of datatype datetime.
When I try to insert values into the datetime column I am getting error.
Incorrect syntax near '-'
My datetime picker has custom format yyyy-MM-dd e.g (2012-11-01)
Following is the code sample I used to insert datetime.
System.DateTime myDate = default(System.DateTime);
myDate = DateTimePickerPrint.Value;
string query = string.Format("EXEC Save_Quotation_Bookshop '" + txt_QutationNo.Text + "','" + txt_CusCode.Text + "',#" + myDate + "#,");
Please any one have an idea ?
First off: STOP concatenating together your SQL code! This is an invitation for SQL injection attacks, and it's really bad for performance, too - use parametrized queries instead.
If you do - you won't have the problem of datetime/string conversion issues, either.....
Secondly: the "safe" format for a date-only DateTime in SQL Server is YYYYMMDD - without any dashes - only this format guarantees that it'll run on any SQL Server, regardless of your language, regional and dateformat settings.
Thirdly. if you want to execute a stored procedure - I would recommend using this approach:
System.DateTime myDate = default(System.DateTime);
myDate = DateTimePickerPrint.Value;
using (SqlConnection con = new SqlConnection(your-connection-string-here))
using (SqlCommand cmd = new SqlCommand("dbo.Save_Quotation_Bookshop", con))
{
// tell ADO.NET it's a stored procedure (not inline SQL statements)
cmd.CommandType = CommandType.StoredProcedure;
// define parameters
cmd.Parameters.Add("#QuotationNo", SqlDbType.VarChar, 50).Value = txt_QutationNo.Text;
cmd.Parameters.Add("#CustomerCode", SqlDbtype.VarChar, 25).Value = txt_CusCode.Text;
cmd.Parameters.Add("#SaleDate", SqlDbType.DataTime).Value = myDate;
// open connection, execute stored procedure, close connection again
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
Don't use EXEC ...... as an inline SQL statement - tell ADO.NET that you're executing a stored procedure, supply the parameters - and you're done!
Wrap the date in single quotes instead of #.
This string concatenation is a SQL injection waiting to happen. Use SqlCommand with parameters instead, then you don't have to worry about string conversion issues
Try this
string query = String.Format("EXEC Save_Quotation_Bookshop '{0}','{1}','{2}'",txt_QutationNo.Text,txt_CusCode.Text, myDate);
OR
string query = string.Format("EXEC Save_Quotation_Bookshop #QutationNo,#CusCode,#myDate");
...
comm.Parameters.AddWithValue("#QutationNo", txt_QutationNo.Text);
comm.Parameters.AddWithValue("#CusCode", txt_CusCode.Text);
comm.Parameters.AddWithValue("#myDate", myDate);

got ORA-01843 when I try to insert date & time to Oracle

I have A anb B in String format
A = 14/01/2007
B = 22:10:39
I try to insert date and time:
SQL = "insert into MyTbl(Tdate,Ttime) value ('" + Convert.ToDateTime(A) + "','" + Convert.ToDateTime(B) + "')";
i got ORA-01843 error, what I can do ?
thank's in advance
Don't use raw SQL to insert values. Use a parameterized query instead. Parse your strings into .NET DateTime (or DateTimeOffset) and TimeSpan values in the normal way, and then use something like:
string sql = "insert into MyTbl(Tdate,Ttime) values (:date, :time)";
using (OracleCommand cmd = new OracleCommand(sql, connection))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.Add("date", OracleType.DateTime).Value = date;
cmd.Parameters.Add("time", OracleType.IntervalDayToSecond).Value = time;
cmd.ExecuteNonQuery();
}
(Obviously adjust for the types of your actual fields.)
The error is due to the month, try:
TO_DATE(A, 'DD/MM/YYYY')
Remember that Oracle doesn't have a time-only field.
You're trying to insert a time-only field into a datetime. My guess is that the CLR is turning B into 00/00/00 22:10:39, which isn't a valid oracle date. For example:
SQL> select to_date('00/00/00', 'MM/DD/YY') from dual;
select to_date('00/00/00', 'MM/DD/YY') from dual
*
ERROR at line 1:
ORA-01843: not a valid month
Either way, Convert.ToDateTime(B) probably isn't returning the right thing.
Also, this:
"insert into MyTbl(Tdate,Ttime) value ("
should be this:
"insert into MyTbl(Tdate,Ttime) values ("
...but I'm guessing that's just a typo here.
However i tried Jon method, it didnt work for me for date also time. So i found this method for datetime. Maybe that helps someone in next future too.
OracleParameter oPrm;
oPrm = cmd.CreateParameter();
oPrm.ParameterName = ":myDate";
oPrm.OracleDbType = OracleDbType.Date;
oPrm.Value = DateTime.Now; //for date
cmd.Parameters.Add(oPrm);

Categories

Resources