SQL Statement - Java - sql

I've been trying to come up with a couple of SQL statements on how to get this right but no luck. I've tried between, >= and =<. Basically, the SQL statement that I've used is working but to an extent only.
My code works like this: the user will choose a date range (from date and to date) and the program will retrieve and show the data it has within those range. Like I said, it works but it also shows the days from the other months when what I want to show is just those particular days that the user picked. eg. from July 1, 2016 to July 5, 2016. What's happening is any month of the year that has those dates will show as well which makes that particular method a bit useless.
Any help or any explanation why is this so would be appreciated.
Below is my code:
stringFromDate = sdf.format(fromDate.getDate());
stringToDate = sdf.format(toDate.getDate());
String query = "Select * from tblSavings where date between '" + stringFromDate+ "' and '" + stringToDate+"'";
try{
pstmt = conn.prepareStatement(query);
rs = pstmt.executeQuery();
tblList.setModel(DbUtils.resultSetToTableModel(rs));

You can use SimpleDateFormat to get a string which is in proper format to be used as a date in SQLite, the proper format being yyyy-MM-dd:
String pattern = "yyyy-MM-dd";
SimpleDateFormat dateFormat = new SimpleDateFormat(pattern);
String stringFromDate = dateFormat.format(fromDate.getDate());

Seems like you're trying to re-invent the wheel here. PreparedStatements were created exactly for this usecase - setting variable values in a predefined structure. In your case, with the setDate method. From the context I'm guessing your fromDate and toDate variables are java.util.Date instances, so you'll have to convert them to java.sql.Dates
java.sql.Date fromDateToBind = new java.sql.Date(fromDate);
java.sql.Date toDateToBind = new java.sql.Date(toDate);
String query = "Select * from tblSavings where date between ? and ?";
try{
pstmt = conn.prepareStatement(query);
pstmt.setDate(1, fromDateToBind);
pstmt.setDate(2, toDateToBind);
rs = pstmt.executeQuery();
// use the results...
} // etc...

Related

Not able to insert date in JDBC

The database I am working with has the date format as
DD-MON-RR
This is the table:
CREATE TABLE dependent (
Fname varchar2(15) not null,
bdate date,
);
I am currently trying to insert into a database using JDBC with the code
String insert = "INSERT INTO DEPENDENT(Fname,bdate) VALUES(?,?)";
PreparedStatement p = z.conn.prepareStatement(insert);
p.setString(1, "Billy");
String formatIn = "DD-MMM-YY";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-AUG-10");
java.sql.Date sqlDate = new java.sql.Date(inDate.getTime());
p.setDate(2, sqldate);
p.executeUpdate();
I thought this would fit the format expected, however it keeps giving me java.sql.SQLException: Io exception: Size Data Unit (SDU) mismatch
I'm unsure how to fix this
Believe it or not, it looks as though your error has to do with the pattern you are using with SimpleDateFormat. Change the following:
String formatIn = "DD-MMM-YY";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-AUG-10");
to this and the problem should go away:
String formatIn = "dd-MMM-yy";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-AUG-10");
The D and Y speciciers denote the day in year and week year, respectively, and are probably not what you intended to use (see here: Y returns 2012 while y returns 2011 in SimpleDateFormat).
Note that the rest of your JDBC code looks OK to me.

How to separate Date and time from DateTime method in ASP.Net

I am writing my SQL query to insert date and time and I want to separate date and time from DateTime method now. I want to store them in a table of my database separately. How I could insert them separately, please guide me.
Here is my incorrect query:
string CheckRequest = "select count(*) from Requests where Date='"+DateTime.Now.ToString()+"'";
DateTime variables in .NET are not 'separable' in date and time parts. They always contains the date and the time (hence the name). What you probably need is to query the database using only the Date part of your query. You could reach your result converting your DateTime variable to a string with just the date part using a special formatting pattern for the ToString method when applied to a DateTime variable
string CheckRequest = #"select count(*) from Requests
where Date='" +DateTime.Now.ToString("yyyy-MM-dd")+"';
but this still leaves an open problem.
Passing a formatted string requires that you format it exactly as your database expects it. Failing to accurately represent the string leads to a failure in retrieving records in the datatable.
A better approach is letting your database engine figure out the Date value from a DateTime variable using a parameterized query.
Something like this
string CheckRequest = #"select count(*) from Requests
where Date=#myDate"
using(SqlConnection cn = new SqlConnection(.......))
using(SqlCommand cmd = new SqlCommand(CheckRequest, cn))
{
cn.Open();
cmd.Parameters.Add("#myDate", SqlDbType.Date).Value = DateTime.Now.ToDay;
object result = cmd.ExecuteScalar();
if(result != null)
{
int count = Convert.ToInt32(result);
MessageBox.Show("Record found=" + count.ToString());
}
else
MessageBox.Show("No Record found");
}
Here I am using a parameter of type Date and assign the Now.ToDay (still a DateTime value but with the time equals to 12:00:00 AM) The database engine now knows to use only the Date part and query your table correctly

2nd Date Parameter Throws ORA-01843: not a valid month error

I have a query where I need to check a date between two dates using Oracle. Whenever I run the code I get an ORA-01843: not a valid month error. However whenever I remove either of the two parameters from the sql it works fine, but trying to use two date parameters throw an error. What am I missing?
StringBuilder sql = new StringBuilder();
DateTime yearBegin = new DateTime(Convert.ToInt32(taxYear) + 1, 1, 1);
DateTime yearEnd = new DateTime(Convert.ToInt32(taxYear) + 1, 12, 31);
sql.Append(
"SELECT * FROM TABLE WHERE FIELD = '1099' AND CREATED_DT >= TO_DATE(:createdYearBegin, 'MM/DD/YYYY') AND CREATED_DT <= TO_DATE(:createdYearEnd, 'MM/DD/YYYY') AND SSN = :ssn");
try
{
using (OracleConnection cn = new OracleConnection(ConfigurationManager.AppSettings["cubsConnection"]))
using (OracleCommand cmd = new OracleCommand(sql.ToString(), cn))
{
cmd.Parameters.Add("ssn", ssn);
cmd.Parameters.Add("createdYearBegin", yearBegin.ToShortDateString());
cmd.Parameters.Add("createdYearEnd", yearEnd.ToShortDateString());
cn.Open();
OracleDataReader dr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
ret = dr.HasRows;
}
}
think you've got a problem with your parameter's order.
If you don't bind parameters by name, they are bound by position (means the order in which you add parameters is taken).
Just try to add :
cmd.BindByName = true;
You expect date formatted as MM/DD/YYYY, but it is not guaranteed that ToShortDateString() returns it in this format. A format specifiction is needed. But well, I do not even know what is the programming language you are using to provide further help...
Print out the results of ToShortDateString and you'll see what happens. Also, i agree with "you should provide a format because you can't rely on the default".

VB.NET 2012 : Select rows from DataView querying with 'Date'

I have a table which contains a date column called PurchaseDate
I have a list box which displays the months. When I click a month , I need to query the dataSource and collect the rows which have the purchase date in the SelectedMonth.
dv2 = New DataView(ds.Tables(0), "PurchaseDate LIKE '" & SelectedMonth & "/%'", "BillNo", DataViewRowState.CurrentRows)
This code is not working. Because here PurchaseDate is in Date format like 'MM/DD/YYYY'. I think I need to convert the date into string before using LIKE operator. I also tried using as below. Even then, it didn't go fine.
dv1 = New DataView(ds.Tables(0), "convert(varchar2(20),PurchaseDate,103) LIKE '" & SelectedMonth & "/%'", "BillNo", DataViewRowState.CurrentRows)
Here SelectedMonth will be a string like '01', '10'..
Use Linq to avoid such issues:
Dim selectedMonth = Int32.Parse(lbMonth.Text)
Dim filteredRows = From r In ds.Tables(0)
Where r.Field(Of Date)("PurchaseDate").Month = selectedMonth
' if you need a new DataTable
Dim tblFiltered = filteredRows.CopyToDataTable()
You don't say what database you are using, so these are the culture independent date literals that I use in the same scenario...
Oracle
TO_DATE('18-Dec-2012','dd-Mon-yyyy')
SQL/Server
'18-Dec-2012'
Ms/Access (not culture independent, but it's the only thing MS/Access accepts)
#12/18/2012#
So you might format your SQL to say something like this...
PurchaseDate BETWEEN '1-Dec-2012' AND '31-Dec-2012'

where clause in select statement - datetime issues

I want to put a where clause in my select statement based on the year and month of a timestamp field in my db
I have a month and a year dropdownlist which give me the following string 01/2012
The date format in my db is "2012-01-01 00:00:00" but when I select an individual date and put it in a message box it converts to "01/01/2012"
I've altered my select statement below to reflect the converted date. However Im still not given the correct details. Any ideas? Is there a particular format that I need to use when dealing with a timestamp field? Can I even use the "Right" function in a select statement?
Dim newRecordDate As String = val1 & "/" & ComboBox2.SelectedValue
Dim sql2 As String = "Select CatA, CatB, CatC, Cost, Currency, MarketingCode, Comment, RecordDate from vw_tblP_Usage_Details where puid = '" & puid & "' right(RecordDate, 7) = '" & newRecordDate & "'"
I say use parameters and the SqlParameter class to pass parameter values to sql server from .NET client instead of using concatenation and string formatting. It makes life easier.
Something Like This:
Dim myDate As Date = DateTime.Now
Dim sql As String = "Select * from SomeTable where MyDate = #some_param"
Using Command As New SqlClient.SqlCommand(sql)
Command.Parameters.AddWithValue("#some_param", myDate)
Using reader As SqlClient.SqlDataReader = Command.ExecuteReader()
'other code here
End Using
End Using