Date Issue with SQL update statement in c# - c#

I have a Date field in a table that is displayed as Day-Month-Year Hour.Minute.Seconds and I am trying to update the HOUR field when there is the same Ertnumber and Date. I can get the field to update with the same Ertnumber but when I try to make sure the date is the same I get an error. I am having troubles making my DateTime format the same as sqls.
I create the DateTime in c# by:
DateTime dateStamp = new DateTime(2013, 2, 14, 1, 0, 0);
Here is my update string.
String.Format("update sdeadmin.meter_data_fixed_network set HOUR{2} = {0} where ERTNUMBER = '{1}' and DATETIME = '{3}'", this.Read, this.ertNumber, this.Stamp.Hour, this.DateStamp.ToString("MMddyyyyHHmmss"));

Try doing something like this:
Datetime parameter for SQL Queries
You should be doing a parameterized query, not a String.Format()

Parameterization of your query should resolve this issue; however, your problem is actually in two parts; you need to first build the query which references a column name that can change, HOUR+stamp.Hour, and the query parameters.
Therefore, something like the following should work for you:
string query =
String.Format("update sdeadmin.meter_data_fixed_network SET HOUR{0} = #read WHERE ERTNUMBER = #ertnumber AND DATETIME = #date;", this.Stamp.Hour);
This builds your basic query - you know have a parameterized query that will update the respective HOUR column of sdeadmin.meter_data_fixed_network. All that remains is create a connection object, a command object, and add the parameters to it before executing it.
For example:
//Create the connection
using(SqlDbConnection connection = new SqlDbConnection("your_connection_string"))
{
//Create the Command
using(SqlDbCommand command = new SqlDbCommand(query))
{
//Set up the properties of the command and the parameters
command.CommandType = CommandType.Text;
command.Connection = connection;
command.Parameters.AddWithValue("#read", Read);
command.Parameters.AddWithValue("#ertnumber", ertNumber);
command.Parameters.AddWithValue("#date", DateStamp);
//Have to open the connection before we do anything with it
connection.Open();
//Execute the command. As we don't need any results back we use ExecuteNonQuery
command.ExecuteNonQuery();
}
}//At this point, connection will be closed and disposed - you've cleaned up
There are several advantages to parameterizing your query:
You can help prevent sql injection attacks
Many database engines can reuse execution plans for parameterized queries, improving performance
#JeffAtwood wrote on this subject a few years ago: http://www.codinghorror.com/blog/2005/04/give-me-parameterized-sql-or-give-me-death.html
Also note the use of the USING statement. This will ensure that the connection and command objects are disposed as soon as you leave the scope of the respective usings. This is important as, although .Net will manage the resources it has control over, it cannot manage external resources like file handles, database connections etc, so it's important you clean up after yourself. The Dispose for Connection will also explicitly close it.

(Assuming you mean SQL Server): The best date format to use with SQL Server is ISO 8601:
yyyyMMdd HHmmss.
HOWEVER, writing your SQL with String.Format is a terrible practice. Use System.Data.SQLClient.SQLCommand with parameters and the format won't bother you.
DateTime dateStamp = new DateTime(2013, 2, 14, 1, 0, 0);
System.Data.SQLClient.SQLConnection cxn; // make sure to set this up and open it
System.Data.SQLClient.SQLCommand cmd = new System.Data.SQLClient.SQLCommand(
String.Format("update sdeadmin.meter_data_fixed_network set HOUR{0} = #value where ERTNUMBER = #ert and DATETIME = #date", this.Stamp.Hour)
,cxn );
cmd.Parameters.Add(new SqlParameter("#value", this.Read);
cmd.Parameters.Add(new SqlParameter("#ert", this.ertNumber);
cmd.Parameters.Add(new SqlParameter("#date", this.Stamp);
cmd.ExecuteNonQuery();

Related

I want to update field with "Datetime" datatype in table of my database from DateTimePicker object in C#

Note: Don't care with Connection becuse the connection work.
Field in database is DateTime
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Value.Date);
cmd = new SqlCommand("UPDATE LAB_TESTING set Lab_Nam='" + lab_id + "',Rslt_lb='" +
textBox1.Text + "',Tst_Dat='" + dtc + "' Where Lab_ID='" +
bindex + "'", con);
con.Open();
cmd.ExecuteNonQuery();
MessageBox.Show("You Update recored successfully", "delete", MessageBoxButtons.OK, MessageBoxIcon.Information);
dataGridView1.DataSource = null;
con.Close();
readdatagrid1();
after Run program , I got Conversion failed when converting date and/or time from character string.
Don't use string concatenation to build your queries (SQL injection alert, also read this!). Use parameterized queries. As for your problem: format the date as yyyy-MM-dd (ISO 8601) and it'll work.
If you'd have used parameterized queries correctly you could've just passed in the DateTime as-is and the driver would've ensured the value would get passed correctly to SQL regardless the "format" / locale setting / whatever since the value would be passed as a DateTime instead of a string. Something like this:
cmd = new SqlCommand(#"UPDATE LAB_TESTING set Lab_Nam = #labnam,
Rslt_lb = #result, Tst_Dat = #tstdat
Where Lab_ID = #id", con);
cmd.Parameters.AddWithValue("#labnam", lab_id );
cmd.Parameters.AddWithValue("#result", textBox1.Text);
cmd.Parameters.AddWithValue("#tstdat", dateTimePicker1.Value.Date);
cmd.Parameters.AddWithValue("#id", bindex);
con.Open();
cmd.ExecuteNonQuery();
Other than that I also recommend to wrap the con and cmd in a using() { ... } statement so that you can be sure this stuff gets disposed properly and that you give your variables and fieldnames decent names and use a consistent naming scheme.
Now repeat after me:
I will never, ever, run queries again that have been string-concatenated together anymore!
From now on I will use parameterized queries
If I need to run string-concatenated queries ever again I will make sure all values are escaped properly
Repeat the above aloud, at least 50 times.
This will work for you.
var date = (DateTime)dateTimePicker1.SelectedDate.Value;
Try this
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Value.ToString("dd/MM/yyyy"));
or else
you can also do this
DateTime dtc = Convert.ToDateTime(dateTimePicker1.Text)
If you are getting this error with your SQL code than have a look here

Insert DateTime with milliseconds into SQL Server

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

How to insert a time column into SQL Server

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)

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

MySQL Database Null Issue

I am currently entering data into a database from a calendar, and I have realized that any new entry I input turns out to be null. All of the data entered is of the same dataype as the column, and I'm confused to as how this is happening. None of the values I'm inputting are null or empty. I have debugged and watched the values to know that.
public static void insertEvent(string date, string title, string eventLocation, string detailsShort, string detailsLong, DateTime startTime, DateTime endTime, DateTime entered, string enteredBy)
{
try
{
string queryString = "INSERT INTO cor(cal_date,event_title,event_location,details_short,details_long,time_start,time_end,entered,entered_by) VALUES (cal_date=cal_date, event_title=event_title, event_location=event_location, details_short=details_short, details_long=details_long,time_start=time_start, time_end=time_end, entered=entered, entered_by=entered_by)";
OdbcConnection conn = new OdbcConnection(MyConString);
conn.Open();
OdbcCommand command = new OdbcCommand(queryString, conn);
command.Parameters.Add("cal_date", OdbcType.DateTime, 30).Value = date;
command.Parameters.Add("event_title", OdbcType.VarChar, 100).Value = title;
command.Parameters.Add("event_location", OdbcType.VarChar, 100).Value = eventLocation;
command.Parameters.Add("details_short", OdbcType.VarChar, 300).Value = detailsShort;
command.Parameters.Add("details_long", OdbcType.VarChar, 300).Value = detailsLong;
command.Parameters.Add("time_start", OdbcType.DateTime, 30).Value = startTime;
command.Parameters.Add("time_end", OdbcType.DateTime, 30).Value = endTime;
command.Parameters.Add("entered", OdbcType.DateTime, 30).Value = entered;
command.Parameters.Add("entered_by", OdbcType.VarChar, 30).Value = enteredBy;
command.ExecuteNonQuery();
conn.Close();
}
catch (Exception)
{
}
}
INSERT INTO cor(cal_date, ...) VALUES (cal_date=cal_date, ...);
The problem is the expression cal_date=cal_date (and similar expressions for every column).
As you're inserting a new row, there is no value for any column yet. So any reference to the column is NULL. The expression NULL=NULL also yields NULL. So you're not inserting values, you're inserting NULL expressions for all columns.
If you change the expression to cal_date=#cal_date it doesn't fix the problem. You're comparing the current value for cal_date (which is NULL) to the value of the parameter #cal_date. An expression like NULL=<anything> always yields NULL.
You should just use parameters, not expressions:
INSERT INTO cor(cal_date, event_tile, ...) VALUES (#cal_date, #event_title, ...);
update: Read the example code in "Pass Parameters to OdbcCommand". That example shows using ? placeholders as #ZombieHunter's answer recommends -- not named parameter placeholders. However, when calling Parameters.Add(), somehow one uses the named parameter with # prefix. Go figure.
nonqueryCommand.CommandText = "INSERT INTO MyTable VALUES (?, ?)";
nonqueryCommand.Parameters.Add("#MyName", OdbcType.VarChar, 30);
nonqueryCommand.Parameters.Add("#MyNumber", OdbcType.Int);
I'm not sure if ODBC supports named parameters together regular SQL statements. The ODBC statements I've seen so far use "?" as placeholder for the parameters.
Certain DBMSs allow an application to specify the parameters to a
stored procedure by name instead of by position in the procedure call.
Such parameters are called named parameters. ODBC supports the use of
named parameters. In ODBC, named parameters are used only in calls to
stored procedures and cannot be used in other SQL statements.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms715435%28v=VS.85%29.aspx
Why don't you use the native MySQL provider for .NET? That would be much faster and probably supports more MySQL specific features.
Also I strongly recommend not using empty catch blocks unless you have a good reason for "consume" that exception.

Categories

Resources