Compare date from database using parameters - c#

string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE (users.ID= " + a.ToString() + ") AND (obroki_save.datum= #datum)";
using (OleDbCommand cmd = new OleDbCommand(queryString,database))
{
DateTime datum = DateTime.Today;
cmd.Parameters.AddWithValue("#datum", datum);
}
loadDataGrid2(queryString);
I tried now with parameters. But i don't really know how to do it correctly. I tried like this, but the parameter datum doesn't get any value(according to c#).

please try this :
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE users.ID= " + a.ToString()+" AND obroki_save.datum= '" +DateTime.Today.ToShortDateString() + "'";
loadDataGrid2(queryString);
when you use with Date, you must write like this
select * from table where date = '#date'
not like
select * from table where date = #date

While it's usually useful to post the error, I'd hazard a guess and say that you're getting a conversion error with your date.
You should really look at parameterising your queries...
You should read this: http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
And if you can't be bothered reading that, then try changing your 'a' variable to '1; DROP TABLE obroki; --' (but only after you back up your database).

Perhaps you need to write your SQL string in the SQL dialect of the database you're using. In Jet/ACE SQL (what's used by Access), the delimiter for date values is #, so you'd need this:
obroki_save.datum= #" +DateTime.Today.ToShortDateString() + "#"
Of course, some data interface libraries translate these things for you, so that may not be the problem here.

Related

C# SQL SELECT not working with WHERE = decimal variable

This is my code:
string query = "SELECT TEKN,KOMMENTAR FROM dbo.JOBBTEKN WHERE JOBBNR = " + jobId + ".00";
SqlDataReader reader = new SqlCommand(query, sqlConn).ExecuteReader();
This is my data:
I want to fetch multiple rows with the exact JOBBNR, but this returns nothing.
EDIT:
The query was working, it was just me being stupid and not searching in the right table. Sorry for wasting anyones time trying to help.
Include the jobId in single quotes. Modify your query to following:
"SELECT TEKN,KOMMENTAR FROM dbo.JOBBTEKN WHERE JOBBNR = '" + jobId + ".00'"
Observe the single quote around jobId.
Looking at the comments, I suspect the datatype of JOBBNR is float; NOT decimel. float datatype internally contains multiple precision, so when you try to match them in WHERE = clause, you may not get result due to mismatched precision.
There are multiple ways to handle this problem. Try something like following:
WHERE JOBBNR BETWEEN 1200.00 AND 1200.01
OR
"WHERE JOBBNR BETWEEN '" + jobId + ".00' AND '" + jobId + ".01'"

Passing DateTime.Now into Access database

I am facing a problem on passing the DateTime.Now into Access database:
oleDBCommand.CommandText =
"INSERT INTO tblData "([PIC], [Sampling Date]) "VALUES (#PIC, #SamplingDate)";
oleDBCommand.Parameters.Add(new OleDbParameter("#PIC", combobox1.Text));
oleDBCommand.Parameters.Add(new OleDbParameter("#SamplingDate", DateTime.Now));
I tried a lot of methods from the internet like using oleDBType.Date, DateTime.Now.ToString(), using AddWithValue..... And none of it is working.
Note 1: Database setting [Sampling Date] = Data Type: Date/Time (Format - Long Time), database was
Note 2: Below code was working but I prefer to using .parameters as it look much more organize and easy to manage.
oleDBCommand.CommandText =
"INSERT INTO tblData ([PIC], [Sampling Date]) " VALUES ('" + combobox1.Text + "', '" + DateTime.Now + "')";
You dont need to pass parameter when specifying current date.
Let the ms access sql query handle it, you need to replace #SamplingDate parameter to Date() for example
cmd.CommandText = "INSERT INTO tblData ([PIC], [Sampling Date]) VALUES (#PIC, Date())";
Here is the best explanation Insert today's date
I was struggling with this this week and the accepted answer really did not help me. I found that if I did the assignment of the date+time as an ODBC canonical string (yyyy-mm-dd hh:mi:ss), it worked just fine. So, my C# code looked something like:
InsertCommand.Parameters.Add("#" + column.ColumnName, OleDbType.DBTimeStamp).Value = DateTime.Now.ToString("u");
for the first row and then
InsertCommand.Parameters.Add("#" + column.ColumnName).Value = DateTime.Now.ToString("u")
for the rest.
Try This,
cmd.CommandText = "INSERT INTO tblData ([PIC], [Sampling Date]) VALUES (#PIC, #SamplingDate)";
cmd.Parameters.Add("#PIC",OleDbType.VarChar).Value = combobox1.Text;
cmd.Parameters.Add("#PIC", OleDbType.Date).Value = DateTime.Now;
c# ms-access

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!

C# query doesn't get executed

Currently I am trying to retrieve the contents of all the entries between a specific date in a MySQL database named 'orders'. To achieve this I use the following code:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and print_location like 'antw'";
dateFrom and dateTill are both variables that contains timestamps.
Everything above works perfectly. The problem that I am facing right now is that I want to check on two print_locations instead of only one. As shown in the code above I only search on 'antw'. The code that I have right now to search on two print_locations is as follows:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and print_location like 'antw' or print_location like 'helm'";
But somehow this doesn't work. I don't get an error the form just freezes and making it unaccessible.
This is probably a simple issue to resolve but I can't seem to solve it. The reason why I am only showing the value of the query variable and not the rest of my code is because everything has worked fine for weeks.
you forgot brackets and you should use parameters to avoid injection attack
string Command = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between #dateFrom and #dateTill and (print_location like 'antw' or print_location like 'helm')";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#dateFrom", yourDateFrom));
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#dateTill", yourdateTill));
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
}
}
Add brackets to your logic:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and (print_location like 'antw' or print_location like 'helm')";
Be careful though... this smells like a potential case of SQL injection!
Never worked with MySQL, but maybe you're forgetting %% on your LIKE clauses. The way it is, it will work like =.
SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and (print_location like '%antw%' or print_location like '%helm%')
You need parentheses on your second set "OR" of conditions:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and (print_location like 'antw' or print_location like 'helm')";
Otherwise, your statement reads like this:
Get me all this stuff, where date between this date and this date, and print_location like 'antw'...
Or get me all this stuff where print_location like 'helm'.
Since you're using a like, it's probably just freezing while executing your query. It would eventually finish, and you'd have way more results than you were expecting.
Also, because of injection concerns, and data modeling, you should really use a data access object model (DAO). I suggest researching it!

"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();
}

Categories

Resources