Using Visual Studio 2010 and C#
Table1:
column datatype
------------------------
Currenttime time
How to insert a time value into table1?
Code
string hr = txtHr.Text;
string min = txtMin.Text;
string time = hr + ":" + min;
insert into table1 values(time)
Getting error
Cannot convert from string to System.Timespan
while inserting into table1.
Need Code help
You should always (no exceptions!) use parametrized queries instead of constructing your own SQL statement as a string! Just google "SQL injection" - it's a really horrible thing.... stop doing that RIGHT NOW
To use a parametrized query, you should get in the habit of using a pattern like this:
// Define your SQL query - WITH parameters!
// And always specify the list of columns for your INSERT!
string query = "INSERT INTO dbo.Table1(CurrentTime) VALUES(#TimeValue)";
// use the "using" blocks to properly protect your disposable connection and command
using (SqlConnection con = new SqlConnection("server=.;database=test;integrated security=SSPI;"))
using (SqlCommand cmd = new SqlCommand(query, con))
{
string hr = txtHr.Text;
string min = txtMin.Text;
string time = hr + ":" + min;
// set the parameter value
cmd.Parameters.Add("#TimeValue", SqlDbType.Time).Value = TimeSpan.Parse(time);
// open connection, execute your INSERT, close connection
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
You need DateTime.Parse and not Timespan.parse , Timespan represents length of time
You need to parse to DateTime and not datetimepicker's itself, parse its value
DateTime.Parse(datetimepicker1.value)
Related
I have a field date in DataTable
jeudi 12 mars 2015
vendredi 13 mars 2015
samedi 14 mars 2015
I need to store it in a table in sql server test which have a column datedes type date
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES('" + dt.Rows[i][j] + "')", con);
command.ExecuteNonQuery();
The code above always return error in conversion date.
how to resolve it ?
You need something like this:
Convert your rows[i][j] to a DateTime
use properly parametrized query in ADO.NET to insert your date
Code something like this:
// this might not work right now - you need to adapt this to that
// you can convert your strings like 'vendredi 13 mars 2015' to a
// valid "DateTime" object
DateTime dateTimeFromRow = Convert.ToDateTime(dt.Rows[i][j]);
// set up your DB connection string
string connectionString = "....";
// define your insert query with PARAMETERS
string insertQuery = "INSERT INTO [test]([Datedes]) VALUES(#DateDes);";
// use "using" blocks to properly dispose of connection and command
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(insertQuery, conn)
{
// define and set value for parameter
command.Parameters.Add("#DateDes", SqlDbType.Date);
command.Parameters["#DateDes"].Value = dateTimeFromRow;
// open connection, execute INSERT, close connection
conn.Open();
command.ExecuteNonQuery();
conn.Close();
}
In your example, you try to insert a string to your date type table column which is wrong obviously.
Depending on what you are doing;
Change your date typed column to nvarchar and insert that string
Parse your string to DateTime and insert that value with parameterized query.
For first option, just change your column type to nvarchar.
For second option, you need parse your string with fr-FR culture (if it is not your CurrentCulture) and pass this value directly.
var s = "samedi 14 mars 2015";
var dt = DateTime.Parse(s, CultureInfo.GetCultureInfo("fr-FR"));
using (var con = new SqlConnection(conString))
using (var cmd = con.CreateCommand())
{
cmd.CommandText = "INSERT INTO [test] ([Datedes]) VALUES(#date)";
cmd.Parameters.Add("#date", SqlDbType.Date).Value = dt;
con.Open();
cmd.ExecuteNonQuery();
}
What you are doing wrong is you try to parse data type string to datetime. And from your information the datetime format is not legal to parse. I suggest you to create another string type's field to store 'jeudi' 'vendredi' or 'samedi'.
Use to cut string :
var targetString = "jeudi 12 mars 2015";
var resultString = "";
int index;
foreach (var item in targetString)
{
if (int.TryParse(item.ToString(), out index) && !string.IsNullOrWhiteSpace(item.ToString()))
{
resultString = targetString.Substring(index);
}
}
//resultString == "12 mars 2015"
Afterthat use :
SqlCommand command = new SqlCommand("INSERT INTO [test] ([Datedes]) VALUES("#date")", con);
command.Parameters.AddWithValue(#date, resultString);
command.ExecuteNonQuery();
Do not append string like you do because it's not secure.
I started a new ASP.NET MVC project two weeks ago. I'm using the micro ORM NPoco and I love it!
During testing I ran into a problem saving DateTime properties into SQL Server 2014 Express.
When I tried to insert the DateTime value 00:03:28.385 it saved in the database as 00:03:28.387. The database column type is time(7). I tried datetime2(7) and the result is always the same -> 00:03:28.387
Then I tried the plain System.Data.SqlClient:
var insert = "insert into Foo(time) values (#time)";
var conn = new SqlConnection(#"conntionString");
conn.Open();
var cmd = new SqlCommand(insertString.ToString(), _conn);
cmd.Parameters.AddWithValue("#Time", DateTime.ParseExact("00:03:28.385", "HH:mm:ss.fff", CultureInfo.InvariantCulture));
cmd.ExecuteNonQuery();
The result was the same: 00:03:28.387
It would worked when insert the time as a string.
insert into Foo(time) values ('00:03:28.385')
So it’s not a problem from NPoco.
If you properly specify the parameters for your SqlCommand, it works just fine:
string connStr = "server=.;database=Test;Integrated security=SSPI;";
string insertQry = "INSERT INTO dbo.Foo(time) VALUES(#Time);";
using (SqlConnection conn = new SqlConnection(connStr))
using (SqlCommand insertCmd = new SqlCommand(insertQry, conn))
{
// use proper Parameters syntax - specify SqlDbType!
insertCmd.Parameters.Add("#time", SqlDbType.Time).Value = TimeSpan.Parse("00:03:28.385");
conn.Open();
insertCmd.ExecuteNonQuery();
conn.Close();
}
I think the .AddParameterWithValue might just guess the datatype wrong and use SqlDbType.DateTime which corresponds to the DATETIME type in SQL Server - and that does have a 3.33ms accuracy - so .385 would be "rounded up" to .387 for that datatype.
I don't know all the details, but see Otiel's answer on this page. It seems to match what you are seeing.
Milliseconds in my DateTime changes when stored in SQL Server
This is due to the precision of the SQL datetime type. According to
msdn:
Datetime values are rounded to increments of .000, .003, or .007 seconds
I'm trying to understand why in C# if you have a sql string why you would have to put tick (') marks in the following where clause in order for this to work. Could someone please explain the reasoning behind this?
where ProgramServer='" + machineName.ToString() + "' and Active=1;
You can avoid those tick (') marks and use Parameters, They will also save you from SQL Injection.
The reason you see those ticks are because SQL expects string type values to be enclosed in single ticks.
What you're seeing is a dynamically built SQL query in the code. When querying based on a string value, the string must be wrapped in single quotes. The final SQL string would look something like:
select * from someTable where ProgramServer = 'YourMachineName' and Active = 1;
Unfortunately, that is far from the best way to do things. You should be using parameterized queries instead:
var query = "select * from someTable where ProgramServer = #machineName and Active = 1;";
using(var conn = new SqlConnection(connString))
{
var command = new SqlCommand(query, conn);
command.Parameters.Add("machineName", machineName.ToString());
// Execute and get the results
}
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);
if you please help me out my error is:
Conversion failed when converting date and/or time from character string.
my database column is of type datetime
Use a parameterized query and you won't have to worry about date formats, or sql injection, and use using to ensure your connection is disposed.
using (var connection = new SqlConnection(yourConnectionString))
using (var command = connection.CreateCommand())
{
command.CommandText = "insert into YourTable(Col1, Col2) values(#val1, #val2)";
command.Parameters.AddWithValue("#val1", 123);
command.Parameters.AddWithValue("#val2", DateTime.Now);
connection.Open();
command.ExecuteNonQuery();
}
you can also GETDATE() function of sql it is predefine function of sql