Using C# & Mysql
When i get the input date in the textbox it should compare with date from table, if it is equal it should throw error message, it should allow only the greater than date
For Example
Table1
ID Date
001 2010-08-05
002 2010-08-02
....
When i enter the date in the textbox like - 2010-08-04, it should compare with Date in the table1, if it is equal or less than max(date) from table1 then it should throw a error message, otherwise it should allow to insert a date.
Am new to mysql & c#, How to do this in c# & Mysql.
Need some code help.
I would first run a Query and fetch the max date to my front end application... Then depending on whether the application is a web application or windows application, I will use this value in Compare Validator (ASP.NET) or Textbox_Validating event to compare the values...
In case you are not familiar as to how to use Compare Validator or the Validating event, let me know, I can post some links here.
In case you want to put this restriction in your Table itself, you may need to use constraints / triggers... I dont know MySql much to help you here.
Related
I have a date search field in my ASP.Net application where the user enters the date he's looking for and the SQL query looks for the exact date provided.
I'm asked to allow the user to enter the date search using wildcards as follows:
- */12/2015 would mean get all the month of December, 2015
- */*/2015 would mean get all the year of 2015
- */*/* would mean get all the data you got
The only way I could think about to do this is to look in my C# code for '*' in the date, if it exists I will replace the query by a date range based on the position of the *.
This solution doesn't look practical to me, is there an easier way to do it in C# or SQL ?
the solution you found is the only one that makes sense while properly handling the information.
what you've been asked for is to give the users 'something' that allows them to search the dates as text and imho there are 2 possible solution:
the one you found (imho the 'right' one)
store the date as formatted string (BAD, AVOID, NIGHTMARE)
the wildcard approach would be simple to implement should you (wrongly, badly, poorly) store the date information and the format in a text field but this would prevent you from manipulating any date as a date and will put you in huge troubles at the first request that involves date handling (consolidation by month, calculate any rate in a given time span, etc...) or if you happen to have users in different countries (that expect a format different from the one stored into the text field).
implementing the search logic in the frontend the database will store the information using the correct data type and all the manipulation needed to accomplish the 'search the date as text' task are performed by the frontend that will feed to the RDBMS a set of parameters that allows it to handle the date properly.
the result would be as follows:
*/12/2015 --> between '20151201' and '20151231'
*/*/2015 --> between '20150101' and '20151231'
*/*/* --> no filter at all
if stored procedures are in use instead the result would be a couple of date parameters filled with the date values.
I would do as you already suggested and parse the search-string. Then depending on the search-string you can select your data. However you do not have to create dateranges, you can use YEAR and MONTH isntead.
Your SQL-Query could look something like this
SELECT * FROM YourTable WHERE YEAR(YourDate) = 2015 and MONTH(YourDate) = 12
In SQL you can replace * with % and use LIKE. Here is one example:
SELECT *
FROM (
SELECT cast('20150611' as date) as dateColumn
UNION
SELECT cast('20150610' as date)) as X
WHERE convert(varchar, dateColumn, 103) LIKE N'%/06/2015'
Keep in mind that this is practical and not the best solution from performance point of view.
I need to insert expiration date of credit card into database.
But i have only date and year dropdown.There is no dropdown for month.
If i am using this way then it gives error,because without month dateformat is wrong.
cmd.Parameters.AddWithValue("#ExpirationDate", dobday.Value & "-" & dobyear.Value)
Please suggest me how i can insert this in database.
You have three options.
The first is to modify your database so that the expiration date is a char(4). Then store it as MMYY. You don't need the dash or even day part for processing.
The second option is to modify your query so that you pass the day part as "1". So a CC that expires in December or 2012 would be 12/1/2012. Of course, your code should drop the day when you are doing something with it.
Personally, I'd go with option three. Don't store it at all. There is simply zero reason to store cc details in any database. Nearly all CC transaction providers provide much better ways of handling recurring transaction where your system doesn't have to keep that info around. If you are working with one that doesn't, then change providers as they are way behind the times. Otherwise you are playing with fire.
(from comments)
datatype of columns is datetime but here i am trying to insert by making them string
Yeah, don't do that. If the datatype is datetime, then construct a DateTime:
var expiry = new DateTime(/* whatever you need here using dobday / dobyear */);
cmd.Parameters.AddWithValue("#ExpirationDate", expiry);
I'll separate this post in 3 sections to be as clear as possible. The first one will be informations you need to know. Second one will be the solutions I tried so far to get this working. Third section will be the questions. I also have to precise that's the first time I'm using CrystalReports.
Informations
I'm currently working with Visual Studio 2010 with C# and I'm using SAP Crystal reports. I'm displaying the data using MySQL database.
Now, here are the tables I use to display the report:
Table : orders
Fields : id(primaryKey), date(DATE), quantity(INT), fksizes(INT), fkclients(INT)
Table : sizes
Fields : id(primaryKey), name(VARCHAR(30)), price(FLOAT)
Relationship between these 2 tables : orders.fksizes with sizes.id
Basically, I'm passing a range of dates as parameters to the Crystal Reports to display informations only between those dates. Then, I created 2 parameters : StartDate and EndDate both of type Date.
What I've tried
Here's the original query I'm using to display what I want without the date range condition :
SELECT sizes.name, SUM(orders.quantity) AS totalQty,
(SUM(sizes.price) * orders.quantity) AS totalPrice,
orders.date
FROM orders
INNER JOIN sizes ON orders.fksizes = sizes.id
GROUP BY sizes.name, orders.date
This query works correctly and display the total quantity sold and the total price for each size name. At the report's footer, I'm using a Summary field in which I got the total sum of all totalQty named sumTotalQty. I have another field for the same purpose for totalPrice named sumTotalPrice.
I have 2 rows of data test which are :
Size name Quantity sold Total Price
------------------------------------------------------------------------------
Big 2 $6.00
XBig 7 $28.00
The field sumTotalQty displays 9 and sumTotalPrice displays $34.00 which is exact results. I have to precise that the first row has 2013-10-29 as value for orders.date and the second one 2013-10-30.
Now, I want to select a range of dates for which I want to display the results. As an example, I select from 2013-10-30 to today, I should get only the second row with sumTotalQty displaying 7 and sumTotalPrice displaying $28.00. I got the single row correctly displayed, but sumTotalQty displaying 9 and sumTotalPrice displaying $34.00 which are incorrect following the date range.
I then tried to add a WHERE clause to my sql query to specify the date range like this (in Database --> Database expert...):
SELECT sizes.name, SUM(orders.quantity) AS totalQty,
(SUM(sizes.price) * orders.quantity) AS totalPrice, orders.date
FROM orders
INNER JOIN sizes ON orders.fksizes = sizes.id
WHERE orders.date BETWEEN '{?StartDate}' AND '{?EndDate}'
GROUP BY sizes.name, orders.date
I got no result displayed with it. So, I think {?StartDate} and {?EndDate} are just not set but I'm really not sure. The same goes for WHERE orders.date BETWEEN #StartDate AND #EndDate.
Questions
Why aren't {?StartDate} and {?EndDate} set even if I have entered a date range when I'm prompted to give them ?
With the original query (without the WHERE clause), how can I get the right result in my summarize fields with the date range given ? It's like it sums from the database and not from the report fields.
EDIT
After many searches, 2 other questions came in my head :
Is it possible to add DateTimePicker in the report so the user will be able to enter a starting date and an end date easily ? The report would be refreshed automatically after that.
Is there a way to create or use Crystal Reports events (OnLoad, AfterLoad,...) ?
Thank you for all help I'll get.
Question 1: You either use BETWEEN (? AND ?) or BETWEEN (#StartDate AND #EndDate)
Question 2: You would have to group your data and then use totals in your report.
Edit: After discovering that the issue is with the parameter declaration, I suggest taking a look at some of the following posts:
http://www.dotnetperls.com/sqlparameter
Why do we always prefer using parameters in SQL statements?
Do some more research and you will find lots of info on the net. What I would suggest is to add some input boxes (TextBox, DateTimePicker, etc.) to your page where the user can input the parameter values and then pass them programmatically to the report. That way you can pass the parameters to the SQL statement and get the correct data to your report. You also won't need parameters in your report.
As far as CR events go, there is the Init event, which is public
http://msdn.microsoft.com/en-us/library/aa691447(v=vs.71).aspx
and then there are some Viewer events that could be useful
http://msdn.microsoft.com/en-us/library/ms227097(v=vs.80).aspx
I have an application where I register some information into the database where I have a Column (DateTime). In this column I insert the date from a DateTimePicker.
Now I want to make a search button which searches according to the date chosen from Comboboxes... but in this Comboboxes I left only one option, to select MONTH and YEAR... how can I make an SELECT query that selects all information according to the Month and Year chosen from the ComboBoxes?
select * from <table>
where month(searchDate)=Month_from_box and Year(searchDate)=Year_from_box
However, depending on the size of your data, this might not be the fastest approach. If you data is in the 100's or even 1000 rows, this approach might be OK...
Another approach would be to build starting and ending dates in C# from your input and then perform a range search
select * from <table>
where searchDate between Start_date_from_C# and End_Date_from_C#
If you go that approach, be sure to consider the time portion, make it 0 in first date and 23:59:59 in the End Date
If you have an index on the date field, the second approach will be faster...
All solutions which use either the datepart or month and year functions make it impossible for the server to optimize the query by using an index.
The only valid solution in terms of performance is #Sparkys second approach using the between clause. He also described the problems arising with the time fraction. That is why I would prefer using a plain date column (instead of datetime). Then you can write
select *
from YourTable
where DateColumn between <FirstDayOfSelectedMonthAndYear>
and <LastDayOfSelectedMonthAndYear>
because when using a datetime column and the range of
between '20121201' and '20121231 23:59:59'
Everything after the last second of the year and midnight still gets discarded. Although it is very unlikely it is technically not correct.
#Nicarus suggests widening the ending time to 23:59:59,997'. This seems to work but is 'ugly' (but, wtf, it works!)
Make sure you store the combo values into Integer variables in your C# before putting them in the SQL query. As others have alluded, SQL Injection attacks are possible if you allow the direct user input to be placed inside a SQL String.
Assuming you have 2 int variables "intMonth", "intYear", and the field name of "dateFieldname", the following SQL should work.
SELECT *
FROM [table]
WHERE datepart[mm,dateFieldname] = intMonth
AND datepart[yyy,dateFieldname] = intYear
Something like this
Select * from tablename where
datepart(mm,datecolumnname)=#cmboxMonthvalue nd datepart(yyyy,datecolumnname)=#ComboboxYearvalue
I want to save entries to a database table depending on the DateTime entered. I have a different model and partial view for each month in the year. Users can create events, I want the events to be saved to the corresponding month table in the db so I can return it to the correct view.
So I need some sort of if statement that says 'if the month value of the entered DateTime is x save to tabel x, if y save to y' and so on.
The user will navigate from month to month and pick dates from a html table styled like a calendar, so the entries need to be inserted to the section of the calendar that corresponds to the datetime. This is just to explain why I need this functionality.
If someone can reccomend a more elegant and functional method of achieving this, go right ahead!
I'm sorry I don't have code to post, I have tried a number of ways and failed. I will post code tomorrow morning when I'm at my computer, but this seems quite simple and I'm very new to this lark so if someone could shed light now, that would be great.
Thanks in advance!
Don't break it out into 12 separate tables. Store them in a single table. You could create a computed column that tells you the month number by calculating it from the DateTime value you're already storing. If your REALLY need to, you can create 12 views off of this table rather easily but I'd take the approach of adding time parameters to your query's WHERE clause. Make sure you index on the DateTime column.