I have a strange problem...I have a MySql db with some columns and one of the column is date_purchased which is of type date_time.
I am using C# and made a DatetimePicker and user selects a date.
private void dateTimePicker1_ValueChanged(object sender, EventArgs e)
{
varDate = dateTimePicker1.Value;
}
Now the problem is I have to compare the two datetimes (one from the database and one from the User) and I should display the records that are less than the date selected by the user(varDate).
select * from orders where date_purchased < = '" + varDate + "'";
I am executing this query but i am getting an exception
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '= '12/25/2011 8:01:31 PM'' at line 1
I wrote the connection string and all and I am struck at the query.
Any Help will be much appreciated...
Thanks,
Subash
You have not given any details on what you are using to run the select query; however, if you are using the connector provided by Mysql (Connector/Net) then you should be using parameters. Which would look something like this:
String sql = "select * from orders where date_purchased < #DatePurchased";
MySqlDataAdapter adapter = new MySqlDataAdapter(sql, connection);
adapter.SelectCommand.Parameters.Add("DatePurchased", MySqlType.DateTime).Value = varDate;
adapter.Fill(dataSet);
Using parameters will ensure the values are converted and will also prevent SQL Injections
Try something like where DBdatetime < "'" + vardate + "'"
One word of caution, check the formats of the two dates. I had a problem in a previous app where the DB had seconds and milliseconds, whereas the app provided just a data and set the time to 00:00. This resulted in records for the current date not showing in the result set. Thus, I had to add 23:59 to the date to get all the records for the current day.
You can retrieve the values between the two data using the following MySQL Query
SELECT * FROM table_name WHERE dbvalue < varData
Related
This question is an extension to another I asked Here
I have a win form which has checkbox controls in it. The names of the checkboxes matches column names of a table. I can not normalize the tables cause of huge data involved, already received for the live project. so everything stays as it is.
I get the selected checbox names as a csv col1,col2,col3 which later i concatenate it to sql string.(no SPs as its a sql compact 3.5 sdf dbase).
In my GetData() method of the DataAccess class i form the sql string. But to avoid sql injections how can ensure that the column names passed are validated.
// Get Data
// selectedMPs: string csv, generated from the list of selected posts(checkboxes) from the UI, forming the col names in select
public static DataTable GetDataPostsCars(string selectedMPs, DateTime fromDateTime, DateTime toDateTime)
{
DataTable dt;
//string[] cols = selectedMPs.Split(','); //converts to array
//object[] cols2 = cols;//gets as object array
//=== using cols or cols 2 in String.Format does not help
// this WORKS, but as i am aware its prone to injections. so how can i validate the "selectedMPs" that those are columns from a list or dictionary or so on? i am not experienced with that.
string sql = string.Format(
"SELECT " + selectedMPs + " " +
"FROM GdRateFixedPosts " +
"WHERE MonitorDateTime BETWEEN '" + fromDateTime + "' AND '" + toDateTime +
using (cmd = new SqlCeCommand(sql,conn))
{
cmd.CommandType = CommandType.Text; //cmd.Parameters.Add("#toDateTime",DbType.DateTime);
dt = ExecuteSelectCommand(cmd);
}
return dt;
}
this WORKS, but as i am aware its prone to injections. so how can i validate the "selectedMPs" that those are columns from a list or dictionary or so on? i am not experienced with that. I would really appreciate your help. Thanks in advance.
This is the only possible approach, and there is no risk of injection with SQL Server Compact, as that database engine only executes a single statement per batch.
So I am creating a search function within my windows form that will allow the user to search for records based on what they have entered into the textbox. I have working code for finding records based off of every filter but the DateTime one. for example:
if (customerID_rb.Checked == true)
{
sqlQuery = "SELECT CustomerID, CustomerName, Telephone, DateAndTime, Status, Description from Calls WHERE CustomerID = " + item;
//'item' is the text in the textbox
UsingCommand(conn, table, sqlQuery);
return table;
}
private static void UsingCommand(SqlConnection conn, DataTable table, string sqlQuery)
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, conn))
{
using (SqlDataAdapter da = new SqlDataAdapter(cmd))
da.Fill(table);
}
}
This will show the records containing the user entered text in the CustomerID column.
However I cannot quite figure out how to do the same but for DateTime. I know that in SQL you type 'WHERE 'DateTime = ...' but no matter how I try to reword the query string I just cannot get it to work.
The error I am getting is : 'SqlException was unhandled: An expression of non-boolean type specified in a context where a condition is expected, near 'DateAndTime'.
Code:
sqlQuery = "SELECT CustomerID, CustomerName, Telephone, DateAndTime, Status, Description from Calls WHERE DateTime DateAndTime = '" + item +"'";
I have tried with and without the DateTime and in multiple different orders, if anyone can help me with this it would be greatly appreciated!
Thanks
Edit:
Ok... I messed up a little. I wrongly assumed you would need the DateTime. However, I may have been thrown off into thinking that because I get thrown an exception if I input the date and time wrong. Thanks! :)
You should never concatenate parameters into a SQL string.
It leaves you vulnerable to SQL injection attacks.
It creates performance problems, as each unique value will create a new SQL query, having a different hash for the query, which defeats the execution-plan caching mechanism of the query engine.
For date values, the ordering of y/m/d, d/m/y, or m/d/y string formats can be different depending on the current culture settings, the OS globalization settings, and the database server's globalization settings. If they're not all in sync, then you could end up with random weirdness like mistaking January 3rd for March 1st.
Instead, you should always parameterize your queries! The query gets a placeholder for the value, and then you add the value using a separate parameter. I'm not going to give you an example here, as it takes very little time to search for this on your own and there have already been hundreds of posts on this here on S.O.
You don't need to specipy the datatype DateTime, Just write the query with column name only like
sqlQuery = "SELECT CustomerID, CustomerName, Telephone, DateAndTime, Status, Description from Calls WHERE columnname = '" + item +"'";
Generally speaking, best would be to add sql parameters, but in string format:
" ... WHERE DateAndTime = '" + item.ToString("yyyyMMdd") +"'"
The yyyyMMdd should be safe to use in all cultures.
The above is assuming, you have to search a date, not including time. Mostly times are only searched on with greater or smaller than.
Additional, if the date field itself contains time, and you only want to search the date:
".... WHERE cast(DateAndTime as date) = '" + item.ToString("yyyyMMdd") +"'"
I am developing a gym membership program on visual studio using C# and sqlite. On every employee-log in attempt, I want the program to check for expired customers where ExpiryDate(Attribute in the table Customer) is less than today's date. this is the piece of code I used:
string sql2 = "delete from Customer where ExpiryDate<' " + DateTime.Today + " ' ";
SQLiteCommand command2 = new SQLiteCommand(sql2, m_dbConnection);
command2.ExecuteNonQuery();
Why not use SQLite built-in functions?
delete from Customer where ExpiryDate<DATE('NOW')
Aren't you missing something like
delete from Customer where ExpiryDate<DATE('NOW') AND Costumer_id=?
Use a parameterized query and your problems in converting a date to a string will evaporate
string sql2 = "delete from Customer where ExpiryDate < #td";
SQLiteCommand command2 = new SQLiteCommand(sql2, m_dbConnection);
command2.Parameters.AddWithValue("#td", DateTime.Today);
command2.ExecuteNonQuery();
Of course this is also the recommended way to avoid Sql Injections but in this case is not your main concern.
By the way, I agree with comments in your question above. Probably it is better to allow a bit of flexibility in the calculation of the deadlines. For example you could add a configuration option that set the maximum number of days allowed after the deadline and add it to the DateTime.Today value.
I have a table stored in SQL Server database. One of the fields of the table is of type DATETIME. I also have a ASP Calendar whose date is compared with the DATETIME filed of Database.
The problem is I don't want to compare the time. Only dates has to be compared. What is the SQL query for doing so.
This is what I used:
SqlCommand myCommand = new SqlCommand("
SELECT AUDIT.AUDIT_DETAILS, USERS.USER_NAME, AUDIT.DATE_TIME, IP
FROM USERS JOIN AUDIT ON (USERS.USER_ID = AUDIT.USER_ID)
WHERE USERS.USERS_NAME LIKE '%"+TextBox1.Text+"%' AND CONVERT(VARCHAR(10),AUDIT.DATE_TIME,110) like "+Calendar1.SelectedDate.Date+"'%'", conn);
I'm getting correct output in the SQL Server explorer but when run from browser through asp.net the query result is empty
Try modifying your query as below
SqlCommand myCommand = new SqlCommand("SELECT AUDIT.AUDIT_DETAILS, USERS.USER_NAME, AUDIT.DATE_TIME, IP
FROM USERS JOIN AUDIT ON (USERS.USER_ID = AUDIT.USER_ID)
WHERE USERS.USERS_NAME LIKE '%"+TextBox1.Text+"%' AND
CONVERT(VARCHAR(10),AUDIT.DATE_TIME,106) == CONVERT(VARCHAR(10),CAST('"+Calendar1.SelectedDate.Date+"' as DATETIME),106)", conn);
You can get only date from Datetime in SQL like this
CONVERT(DATE,GETDATE())
And after that you can compare to that value.
I'm a newb here, and it may be because I've been up since yesterday morning, but I can't find my error here in this insert statement. My handler asked me not to parameterize for this training project (it won't be deployed), so no worries for the injection vulnerabilities. Anyway, the query's right, the data types are correct, and the table and field names are spelled correctly. What am I missing here? And is there a better way to find it than just staring at the screen until it comes to you?
protected void BtnSubmit_Click(object sender, EventArgs e)
{
string x = Request.QueryString["SubId"];
string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string comQuery = "INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES ('" + "decline" + "', '" + TbComments.Text + "', 2) WHERE SubmissionId =" + x;
using (SqlConnection sqlConn = new SqlConnection(connectionString))
{
sqlConn.Open();
using (SqlCommand comCmd = new SqlCommand(comQuery, sqlConn))
{
comCmd.ExecuteNonQuery();
}
}
}
An INSERT can't have a WHERE clause. It makes no sense to have one, you're putting data in, not narrowing it down.
If you're trying to change preexisting data, that's an UPDATE, not an INSERT. Here's an example:
"UPDATE Submission
SET Status='decline', StatusComment='" + TbComments.Text + "', StatusValue = 2
WHERE SubmissionId = " + x
That is incorrect INSERT syntax. Correct INSERT syntax is:
INSERT INTO tableName (columnList) VALUES (valueList)
columnList and valueList must have same count of items and values must be of type expected by columns.
or
INSERT INTO tableName (columnList)
SELECT columnList2
FROM tableName2
WHERE conditionsFromTable2
columnList and columnList2 must have same count of items of same types. You can use any complicated select joined over multiple tables with condition applied on data from these tables.
You need to use UPDATE, not INSERT
INSERT insert new row, therefore WHERE makes no sense
Where clause is not allowed in Insert query. Form your code I guess that you need to use Update query.
You'r trying to INSERT INTO Submission data from TbComments. So you need to SELECT the data from TbComments and then INSERT INTO Submission
string comQuery =
"INSERT INTO Submission (
Status,
StatusComment,
StatusValue)
SELECT
'decline',
TbComments.Text,
2)
FROM TbComments
WHERE SubmissionId =" + x;
So your SQL statement is:
"INSERT INTO Submission (Status, StatusComment, StatusValue) VALUES (blah) WHERE SubmissionId =" + x;
The problem is definitely the WHERE. WHERE isn't valid for INSERT - See the MSDN documentation for the Insert command. Since you're filtering by SubmissionId, you probably want to do an UPDATE instead.
As for a better way of finding the problem, learning to use the MSDN documentation is a good step. A quick Google search for "msdn t-sql insert" will give you the page I linked to earlier in this answer. Documentation, experience, Google and Stack Overflow. That's how you find solutions :)