I need help with my comboboxes.
An application to the value selected in the first combo imported dates in the second and the third combo combo. Only the dates look like this:2009-01-01 12:00:00AM. I want to cut 12:00:00AM. My query is:
string command2 = "select God_MinQ,God_AverQ,God_MaxQ,min(Dat) from hydgod where station='"
+ comboBox1.SelectedItem.ToString() + "' and Dat between '"
+ comboBox2.SelectedItem.ToString() + "' and '" + comboBox3.SelectedItem.ToString()
+ "' group by year(dat),month(Dat)";
Where can I format string in combobox2 and combobox3?
Another thing I wanted to ask you. When the user chooses from combo2 starting date to date as 2009-01-01 to 2010-01-01 Mesagebox out in year 2010, and he has chosen for the year 2009. How can I fix this.
Here is a link to the screenshot:
https://s30.postimg.org/60nuoocdd/Untitled.jpg
If your comboboxes containe DateTime-Values you can format them like this:
DateTime value = (DateTime)comboBox2.SelectedItem;
String valueString = value.ToString("MMMM dd, yyyy");
If you need a differen formationg check out the MSDN Entry
You should really consider using Sql Parameter like #Reniuz suggested.
This prevents SQL Injection attack and helps in general by better readability of your code and easier parsing of values
Related
I am writing Insurance Managment System as project at University.
This is my MySQL commadn:
string lifeQuery = "insert into lifeinsurance values( null, '" + surname.Text + "." + pesel.Text + "', " + double.Parse(lifeInsSumTB.Text) + ", '" + double.Parse(lifeInsPriceTB.Text)
+ ");";
But te problem is that in UWP double is with ',' and to MySQL i need to have it with '.'.
When I try to do this like this: '25,453' it says data truncated. Without ' ', like this 25,453 it says that column count doesn't match value count at row 1, because it interets it as two different values 25 and 453.
So my question is:
How do I insert this double value to my table?
This problem is caused by the implicit conversion to a string when you call double.Parse and then concatenate the result back into the sql text. This requires the compiler to represent the double value as a string and it will use the current culture to do the conversion. Of course the result is not what MySql expect to be a double value.
Moreover using string concatenation to build sql commands leads to Sql Injection hacks. A very nasty problem that you should avoid. Always.
So let's try to add some code to resolve these problems
// A parameterized string without any concatenation from user input
string lifeQuery = #"insert into lifeinsurance
values( null, #surname, #sum, #price)";
MySqlCommand cmd = new MySqlCommand(lifeQuery, connection);
// Add the parameters with value for each placeholder in string
cmd.Parameters.AddWithValue("#surname", surname.Text + "." + pesel.Text);
// Parse the user input as a double using the current culture to correctly
// interpret the comma as decimal separator.
// Note that here I have no check on the correctness of the input. If your
// user cannot be trusted to type a valid double number then you should use
// the double.TryParse approach separating these lines from the actual check
cmd.Parameters.AddWithValue("#sum", double.Parse(lifeInsSumTB.Text, CultureInfo.CurrentCulture));
cmd.Parameters.AddWithValue("#price", double.Parse(lifeInsPriceTB.Text, CultureInfo.CurrentCulture));
cmd.ExecuteNonQuery();
Like other said - there are better ways to send over data with Sql. That being said this answer focuses on addressing your specific problem.
I think your problem may be your language/culture settings.
Try this:
Console.WriteLine(double.Parse("19.2323244").ToString("G", CultureInfo.InvariantCulture));
Output:
19.2323244
https://learn.microsoft.com/en-us/dotnet/api/system.globalization.cultureinfo?view=netcore-3.1#Invariant
I have a sql string now, and I need to send it in, for every day between 2 dates. like, if the first date yould be, 01.01.0001 and the last date would be 03.01.0001 then, the string should be send 3 times in with every date (01. + 02. + 03.01.0001)
Any ideas for I can integrate that in my script when I already need to send the string in for every selected member ID?
That means, if I have 3 IDs, and 3 days, there would be 3 strings for every ID = 9 strings per total.
Please note, that the dates are dynamic as well as the amout of IDs.
For now, I have:
foreach (DataRow row in m_dt.Rows) {
foreach (var item in row.ItemArray) {
string sqlString = "INSERT INTO [table] ([id] ,[day] ,[month] ,[year]) VALUES('" + item + "', '" + reason + "', '10', '08', '2016', '1' )";
Sendin( sqlString );
}
I want to compare date entering from a combobox as string with the date that saved into SQL Server database,then summation some values X but comparison doesn't work ...
string from = (comboBox4.Text+ '/' + comboBox5.Text + '/' + comboBox6.Text+ " 00:00:00 AM");
string to = (comboBox1.Text+ '/' + comboBox2.Text + '/' + comboBox3.Text);
cmd.CommandText = "SELECT * from issued where issued.Date >='" +from + " ' And issued.Date < '" + to + " ' "; //مقارنة الاسم
dr = cmd.ExecuteReader();
if (dr.HasRows)
{
while (dr.Read())
{
item = new ListViewItem(dr[0].ToString());
item.SubItems.Add(dr[4].ToString());
f6.listView1.Items.Add(item);
x += Convert.ToInt16(dr[4]);
}
}
Help me please..
As Marc stated above, you really should be careful of sql injection attacks here. Look it up and do some research because you'll suddenly find you have a compromised server someday.
Is your Date column of type Date or DateTime? If it's DateTime, then simply comparing on a specific date does not include that date for the upper bound. For instance, if your dates are:
From: 1/1/2013
To: 1/1/2014
Then your comparison would not return any values from 1/1/2014, and the last date included in the search would actually be 12/31/2013.
Add a little more specifics to your question regarding what values you are actually sending in your sql and what the types are in your db and you'll get a better answer!
Good luck!
I'm trying to display in a graph (Winforms/C#) the total amount from one column vs unit of time (in this case month) - so it would be a amount vs time graph. The problem is that the user would like the freedom of lets say - choosing the totals for January and June and compare them in a single graph (so the total for the month of January would be represented as a bar next to June's total's bar). I already capture the selected months (also, I have the graph control on the for) within a list but where I am really stuck is to build the mysql statement and its something like this
selectdataforGraph = "SELECT SUM(Amount_Net) AS Total FROM testingproject.incomeinformation WHERE date";
foreach (int month in selectedMonth) {
selectdataforGraph += "between '" + selected_year+ "-" + month +
"'-1 AND '" + selected_year + "-"+month+ "-31' AND";
}
I know it has some space missing and some quotation mark problems - already ran the query and I figured as much but I don't think the in-between would work because I don't know how to AND the next part of it so if a user picks May then August would be between 2007-5-01 and 2007-5-30 AND 2007-8-01 and 2007-8-30???
EDIT: didn't seem MySQL was your DB...
Definitely use a parameterized query! However... to fit in with what you have and so you can test it quickly...
I think I would use DATEPART rather than BETWEEN....
var selectdataforGraph = "SELECT SUM(Amount_Net) AS Total FROM testingproject.incomeinformation WHERE ";
var monthList = string.Join(",", selectedMonth);
selectdataforGraph += " YEAR(date) = " + selected_year;
selectdataforGraph += " AND MONTH(date) in (" + monthList + ")";
I want to filter values from database based on date.
Date in a database contains values like this: 2008-12-28 18:00:00. And my class has a DateTime variable depending on which I want to filter. Ideally it would work like this:
myBindingSource.Filter = "DATE(myDateField) = myDateTime.Date" + adjusting myDateTime.Date format as needed.
But it throws an EvaluateException: "The expression contains undefined function call DATE()."
Although if I execute the SQL statement directly, I can use the DATE() function in filter.
P.S. I use MYSQL DB with the Connector/Net 5.2
How can I solve this problem?
Thank You all for suggestions.
The getSqlDate function is not needed. You can use String.Format() to format dates:
String.Format("{0:yyyy-MM-dd} 00:00:00", myDateTime)
OR
myDateTime.Date.ToString("yyyy-MM-dd") + " 00:00:00"
You could filter the binding source like this:
myBindingSource.Filter = String.Format("myDateField >= '{0:yyyy-MM-dd}' AND myDateField < '{1:yyyy-MM-dd}'", myDateTime, myDateTime.AddDays(1));
Thank you Tom H.
Yes, i wanted to eliminate the time portion of the datetime in the filter and your suggestion works perfectly.
I`ll leave the complete solution for others:
myBindingSource.Filter = "myDateField >= '" + getSqlDate(myDateTime) + "' AND myDateField < '" + getSqlDate(myDateTime.AddDays(1)) + "'";
where getSqlDate function is:
string getSqlDate(DateTime date) {
string year = "" + date.Year;
string month = (date.Month < 10) ? "0" + date.Month : "" + date.Month;
string day = (date.Day < 10) ? "0" + date.Day : "" + date.Day;
return year + "-" + month + "-" + day + " 00:00:00";
}
A correction to the answer:
Accoring to msdn
,to get the correct date
the mm in
yyyy-mm-dd
would have to be capitalized
like so;
yyyy-MM-dd
to get a correctly formatted date.
Is myDateField the name of the field in the dataset? I think you want an expression like this:
myBindingSource.Filter = "myDateField = " & myDateTime.Date.ToString()
Are you asking how to eliminate the time portion of the datetime in the filter? I'm not too familiar with MySQL, but if you use any kind of function that returns the date portion of a datetime then you are likely to kill any chance of using an index on that column for the query (existing or future index).
Your best bet is to create a filter on the front end that checks for a range that is only for your given filter date. For example:
myBindingSource.Filter = "myDateField >= " & <code to create a string representing 12AM of your date> &
" myDateField < " & <code to create a string for 12AM of the next day>
Sorry for not having exact code, but I'm a SQL developer and my lack of VB/C# skills would require me to take a lot more time to come up with the functions then it would probably take you. :)
For search between two date in DataGridView you can use this code :
BindingSource1.Filter = "F5 >= '" + maskedTextBox1.Text + "' And " + "F5 <= '" + maskedTextBox2.Text + "'";
BindingSource1 : my datagridview datasourc load in BindingSource1 .
F5 : name of your header column in datagridview .
maskedTextBox1 : for get first date .
maskedTextBox2 : for get second date .
Be successfull "Arn_7"
For search between two date in DataGridView you can use this code :
BindingSource1.Filter = "F5 >= '" + maskedTextBox1.Text + "' And " + "F5 <= '" + maskedTextBox2.Text + "'";
BindingSource1 : my datagridview datasourc load in BindingSource1 .
F5 : name of your header column in datagridview .
maskedTextBox1 : for get first date .
maskedTextBox2 : for get second date .
You will need to add signle quotes like this "'2021-09-26'".
myBindingSource.Filter = "myDateField = " + "'" + myDateTime.Date.ToString("yyyy-MM-dd") + "'"