I have got the following exception when try to select data from SQL Server or inserting data in in with a C# windows application. I am passing the date in where clause of select query in single quotes like this '16/03/2011' The exception message is shown below:
The conversion of a char data type to
a datetime data type resulted in an
out-of-range datetime value.
Is there any perfect solution for inserting and selecting date from sqlserver database irrelevant to the operating system. i.e. that works on both Italian and English OS.
If you can't use stored procs, or parameterized queries, you might want to format the date in a yyyy-mm-dd format. Ex. '2011-03-16'
T-SQL SAMPLE
INSERT INTO MyTable (SomeDate) VALUES ('2011-03-16')
or
SELECT * FROM MyTable WHERE SomeDate <= '2011-03-16'
Also, keep in mind the time portion of the date. If time is not important, then make sure you don't store it, because it could impact your SELECT queries down the road.
Use stored procedures, or parameterized queries. These will let you pass in a C# datetime object, and the conversion will be handled automatically for you.
I would suggest starting with the SQLDataAdapter class. A simple example of this would be:
using (SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM MyTable WHERE myDate = #myDate", someSqlConnection)
{
da.SelectCommand.Paramaters.Add("#myDate", new DateTime());
DataTable dt = new DataTable();
da.Fill(dt);
}
However, be aware that there are many different ways of achieving your goal. From your question, I would imagine you are creating SQL strings and executing them against your database. This is considered a Bad Practice for lots of reasons (including the one you describe). Read up about ORMs such as Entity Framework or NHibernate.
Related
cmd = new SqlCommand("Select Max(Date_Time) From Daily_Sale ", con); cmd.ExecuteNonQuery();
string date_tim = (string)cmd.ExecuteScalar();
MessageBox.Show("date time" + date_tim);
This shows date time in a message box, but when I call this query:
cmdc = new SqlCommand("Select Total_Sale from Daily_Sale Where Date_Time ="+ date_tim,con);
cmdc.ExecuteNonQuery();
I get a syntax error.
Date_Time is saved as nvarchar(50).
First, you need to use parameters to send data to SQL. Never concatenate strings of data to SQL statement. That's a security hole as it's an open door to SQL Injection attacks.
For more information, read How can prepared statements protect from SQL injection attacks? and Microsoft Docs - How to: Perform Parameterized Queries
Second, Never store dates as strings in your database. For date only values, use the Date data type. For time only values, use the Time data type. For date and time values, use the DateTime2 data type (why not use DateTime?).
For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type, and my answer on SO to this question.
Third, you don't need two queries to get the last value of total_sale from the database. You can do that in a single query, without any parameters at all:
SELECT TOP 1 Total_Sale
FROM Daily_Sale
ORDER BY Date_Time DESC
If you want the date time value as well, simply add that to the query:
SELECT TOP 1 Total_Sale, Date_Time
FROM Daily_Sale
ORDER BY Date_Time DESC
I am building an application in which I will producing some reports based off the results of some SQL queries executed against a number of different databases and servers. Since I am unable to create stored procedures on each server, I have my SQL scripts saved locally, load them into my C# application and execute them against each server using ADO.NET. All of the SQL scripts are selects that return tables, however, some of them are more complicated than others and involve multiple selects into table variables that get joined on, like the super basic example below.
My question is, using ADO.NET, is it possible to assign a string of multiple SQL queries that ultimately only returns a single data table to a SqlCommand object - e.g. the two SELECT statements below comprising my complete script? Or would I have to create a transaction and execute each individual query separately as its own command?
-- First Select
SELECT *
INTO #temp
FROM Table1;
--Second Select
SELECT *
FROM Table1
JOIN #temp
ON Table1.Id = #temp.Id;
Additionally, some of my scripts have comments embedded in them like the rudimentary example above - would these need to be removed or are they effectively ignored within the string? This seems to be working with single queries, in other words the "--This is a comment" is effectively ignored.
private void button1_Click(object sender, EventArgs e)
{
string ConnectionString = "Server=server1;Database=test1;Trusted_Connection=True";
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
SqlCommand cmd = new SqlCommand("--This is a comment \n SELECT TOP 10 * FROM dbo.Tablw1;");
DataTable dt = new DataTable();
SqlDataAdapter sqlAdapt = new SqlDataAdapter(cmd.CommandText.ToString(), conn);
sqlAdapt.Fill(dt);
MessageBox.Show(dt.Rows.Count.ToString());
}
}
Yes, that is absolutely fine. Comments are ignored. It should work fine. The only thing to watch is the scopin of temporary tables - if you are used to working with stored procedures, the scope is temporary (they are removed when the stored procedure ends); with direct commands: it isn't - they are connection-specific but survive between multiple operations. If that is a problem, take a look at "table variables".
Note: technically this is up to the backend provider; assuming you are using a standard database engine, you'll be OK. If you are using something exotic, then it might be a genuine question. For example, it might not work on "Bob's homemade OneNote ADO.NET provider".
Yes, you can positively do it.
You can play with different types of collections, or with string Builder for passing queries even you can put the string variable and assign the query to it.
While the loop is running put in temp table or CTE, its totally depends on you to choose the approach. and add the data to datatable.
So if you want the entire data to be inserted or Updated or deleted then you can go for transaction,it won't be any issue.
I don't use ado.net, I use Entity Framework but I think this is more a SQL question than an ADO.NET question; Forgive me if I'm wrong. Provided you are selecting from Table1 in both queries I think you should use this query instead.
select *
from Table1 tbl1
join Table1 tbl2
on tbl1.id = tbl2.id
Actually I really don't ever see a reason you would have to move things into temp tables with options like Common Table Expressions available to you.
look up CTEs if you don't already know about them
https://www.simple-talk.com/sql/t-sql-programming/sql-server-cte-basics/
I'm working on an app that stores data in a spreadsheet to a Postgresql database. I'm familiar with C# and .Net but not so well with Postgresql. I'm having trouble storing a DateTime value into a TimeStamp column; I keep getting an error message: Failed to convert parameter value from a DateTime to a Byte[]. Any advice would be appreciated.
string query = "INSERT INTO organizer(organizer_name, contact_name, phone, alt_phone, created_date, last_update) " +
"VALUES('#name', '#contactname', '#phone', '#altphone', '#created', '#updated')";
OdbcCommand cmd = new OdbcCommand(query, con);
cmd.Parameters.Add("#name", OdbcType.VarChar);
cmd.Parameters["#name"].Value = org.Name;
cmd.Parameters.Add("#contactname", OdbcType.VarChar);
cmd.Parameters["#contactname"].Value = org.ContactName;
cmd.Parameters.Add("#phone", OdbcType.VarChar);
cmd.Parameters["#phone"].Value = org.Phone;
cmd.Parameters.Add("#altphone", OdbcType.VarChar);
cmd.Parameters["#altphone"].Value = org.AltPhone;
cmd.Parameters.Add("#created", OdbcType.Timestamp).Value = DateTime.Now;
cmd.Parameters.Add("#updated", OdbcType.Timestamp).Value = DateTime.Now;
con.Open();
cmd.ExecuteNonQuery();
I don't have a PostgreSQL db handy to test with, but I believe that you are seeing this because the OdbcType.Timestamp is actually a byte array, not a time and date. From MSDN:
Timestamp: A stream of binary data (SQL_BINARY). This maps to an Array of type Byte.
This is probably because the timestamp datatype, in SQL Server, is
a data type that exposes automatically generated, unique binary numbers within a database. timestamp is generally used as a mechanism for version-stamping table rows.
I would try using OdbcType.DateTime, which seems to map to the concept behind PostgreSQL's timestamp.
EDIT:
Here is a useful post which summarizes the mappings between PostgreSQL and .NET.
You've got a few solutions here...I'm going to assume the organizer table has the created_date and last_update as timestamp fields, correct? The silliest answer is to change those to varchar fields. heh.
2 better answers...I'm assuming this is a formatting error where DateTime.Now doesn't return in the format pgsql wants:
Since you are just giving it the current timestamp
you can define your table to default these columns to now() and then not pass values to this column, on an insert the table would just populate that with the default of now().
instead of defining the variable to DateTime.Now and then passing the variable, just send postgres now() and it will populate it in the format it feels right.
And second potential is to format the date into what PG expects as part of the insert statement...I'd need to know what DateTime.Now gives for a value to format it to what pg wants to see. This might be a bit of string manipulation...
Hi I try to insert into DB date time and the Column is date type what I need to do?
this is the code
string query = "INSERT INTO Feedback (user_Name, date_of_, Praise) VALUES ('"+TextBox1.Text+"',"+DateTime.Now+",'"+TextBox2.Text+"')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
I would advise against using time from the application server to insert values into the database. The most basic example how that can go wrong is that you could have two servers set to different time zones, that use the same database. What server's time is the right time?
Other thing is the neccessary transformation of a datetime to string when you are using inline SQL statements. If the application server and the database server are set to different cultures, you need to be extremely careful not to insert May 2nd (02.05), when you want to insert Feb 5th (02.05).
Sure, all these issues are avoidable, but why bother with them at all, when the RDBMS can do all that for us?
BTW, even if you don't want to use stored procedures, use parameters.
This code should be reformated like:
string query = "INSERT INTO Feedback (user_Name, date_of_, Praise) VALUES (#username, getdate(), #praise)";
SqlCommand cmd = new SqlCommand(query, con);
SqlParameter param = new SqlParameter("#username", SqlDbType.Text);
param.Value = text1;
cmd.Parameters.Add(param);
param = new SqlParameter("#praise", SqlDbType.Text);
param.Value = text2;
cmd.Parameters.Add(param);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
Don't include the value directly in your SQL.
Use a parameterized query instead. There's no point in messing around with string formatting when the database is quite capable of accepting a prepared statement with a DateTime parameter.
You should get in the habit of using query parameters for all values which can't be simply hard-coded into the SQL to start with. For example, your query is currently just blithely taking the contents of TextBox1.Text and inserting that into the SQL. That's a recipe for a SQL injection attack.
You should separate the code (the SQL) from the data (the values). Parameterized queries are the way to do that.
EDIT: Using a built-in function in the SQL is fine, of course, if you're happy to use the database's idea of "now" instead of your client's idea of "now". Work out which is more appropriate for your situation.
Why don't you use a TIMESTAMP column in your database ? Seems like overhead by inserting it through your code.
The following link provides more info:
http://msdn.microsoft.com/en-us/library/aa260631(SQL.80).aspx
edit: Set the default value of your database column as CURRENT_TIMESTAMP (Transact-SQL), and leave the column name out of your insert statement. The current date and time will be inserted by your database automatically. No problem with conversions anymore!
Replace DateTime.Now with DateTime.Now.ToString("yyyy-MM-dd");
Also, you should really parameterize your insert statement so that you cannot fall victim of a SQL injection attack.
There is a NOW() function in most SQL implementations.
You have to convert your DateTime to an Sql DateTime literal. The easiest way to do it is this:
DateTime.Now.ToString(System.Globalisation.CultureInfo.InvariantCulture)
Yet, especially for DateTime.Now, you may use some Sql function, such as GetDate() but that often depends on your database server.
You can use the Date property:
DataTime.Now.Date
here is my query:
select reporttime, datapath, finalconc, instrument from batchinfo
join qvalues on batchinfo.rowid=qvalues.rowid where qvalues.rowid
in (select rowid from batchinfo where instrument LIKE '%TF1%' and reporttime
like '10/%/2010%') and compound='ETG' and name='QC1'
i am running it like this:
// Create a database connection object using the connection string
OleDbConnection myConnection = new OleDbConnection(myConnectionString);
// Create a database command on the connection using query
OleDbCommand myCommand = new OleDbCommand(mySelectQuery, myConnection);
it does not return any results.
when i try this same query in sql server GUI it returns lots of rows
is there a problem specifically with the syntax of the query for c#?
please note that if i simplify the query like select * from table, there is no issue
Can you try using SqlCommand instead of OleDbCommand?
According to MSDN it: Represents a Transact-SQL statement or stored procedure to execute against a SQL Server database.
So if you really are using SQL Server 2008 you should probably use this. Any reason you are not?
How are you setting up the mySelectQuery string?
Could this be a problem with an escape character?
If you're not doing it already,
string mySelectQuery = #"query text here";
Personally I would run query profiler to see what query (if any) is being run, and then go from there.
Are you sure you are connecting to the same database in your code?
On a side note do you need the inner select? Couldn't you write this query as follows.
select reporttime,
datapath,
finalconc,
instrument
from batchinfo
join qvalues on batchinfo.rowid = qvalues.rowid
where compound = 'ETG'
and name = 'QC1'
and batchinfo.instrument like '%TF1%'
and batchinfo.reporttime like '10/%/2010%'
Edit - Never mind, just read the comment that your date is in a varchar field. Will leave this here since it may still be useful information.
Try this:
reporttime like 'Oct%2010%'
I have a test table here and when I query it using
where LastModified like '11/%/2010%'
no rows are returned, although all of the rows in the table have dates in November 2010. When I run the same query using like 'Nov%2010%', it returns all rows.
Details can be found here:
The LIKE clause can also be used to search for particular dates, as well. You need to remember that the LIKE clause is used to search character strings. Because of this the value which you are searching for will need to be represented in the format of an alphabetic date. The correct format to use is: MON DD YYYY HH:MM:SS.MMMAM, where MON is the month abbreviation, DD is the day, YYYY is the year, HH is hours, MM is minutes, SS is seconds, and MMM is milliseconds, and AM designates either AM or PM.