Retrieving data from database using JDateChooser? - java

I want to retrieve only data that have same date_Add and output it to the table_patients
Here is the code
private void btn_GoActionPerformed(java.awt.event.ActionEvent evt) {
java.util.Date chooser= choose.getDate();
java.sql.Date sqlchooser=new java.sql.Date(chooser.getDate());
try{
String sql="select * from Patients_Details where Date_Add='"+sqlchooser+"'";
pst=conn.prepareStatement(sql);
pst.setDate(1,sqlchooser);
rs=pst.executeQuery();
table_patients.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(SQLException sql)
{ sql.printStackTrace(); }
}
but i get this error
Exception in thread "AWT-EventQueue-0" java.lang.ArrayIndexOutOfBoundsException: 0
at org.sqlite.PrepStmt.batch(PrepStmt.java:192)
at org.sqlite.PrepStmt.setObject(PrepStmt.java:245)
at org.sqlite.PrepStmt.setDate(PrepStmt.java:290)
at employeeJFrame.btn_GoActionPerformed(employeeJFrame.java:981)
at employeeJFrame.access$1300(employeeJFrame.java:18)
at employeeJFrame$13.actionPerformed(employeeJFrame.java:391)
error points to this line
pst.setDate(1,sqlchooser);
Could someone please help? NB: I am a java begginer

There are a number of issues here.
You're passing the day of month to a constructor that expects a milliseconds time value. This will result in your sqlchooser date being 1 to 31 milliseconds after midnight on 1970-01-01. If you look at the documentation, you'll see that java.util.Date.getDate()
Returns the day of the month represented by this Date object...
And the constructor java.sql.Date(long)
Constructs a Date object using the given milliseconds time value...
Also be aware that java.util.Date.getDate() is deprecated in favor of Calendar.get(Calendar.DAY_OF_MONTH).
You're setting the date condition explicitly by constructing the SQL string with sqlchooser and are then attempting to set the date as parameter of the prepared statement (but the statement has no parameters). You only need to do one of these. Read to Using Prepared Statements to understand how parameters work.
The first issue will likely result in you receiving no results. The second issue should be causing an SQLException. Neither of these should cause any problem on the line you indicated, but I'd suggesting fixing these problems and moving on from there.
For work with dates going forward, you should consider using Joda Time rather than the base Java date/time API, which many regard as poorly designed.
UPDATE (post provision of exception details)
Post your edit, it's clear that you are receiving this error because you are trying to assign a parameter to a prepared statement that has no parameters (point 2 above). Parameters are represented by the '?' character in statements. See the linked documentation above for details.
If you look at the exception, you'll see it occurs in the org.sqlite.PrepStmt.batch method. The source of this method is:
private void batch(int pos, Object value) throws SQLException {
checkOpen();
if (batch == null) batch = new Object[paramCount];
batch[batchPos + pos - 1] = value;
}
For your statement, paramCount==0, so the batch Object array is created with length 0. The last line then attempts to set the first element (0 + 1 - 1 = 0) to your passed Date object, which is why you get an ArrayIndexOutOfBoundsException.
Bottom line: Read and understand about prepared statement parameters at the link provided.

Related

Android Studio project not reading correctly from SQLite database?

I've been struggling with this for days now and can't work out what's wrong. The thing is, I am not getting errors at the moment. Im just not producing the result I hoped for. I am trying to read from a specific record in my sqlite database where the data is a week ago today - I am trying to get the weather on this day, which is in my database. Here is my DB code for the method I am using:
public long homepageTB(){
LocalDate now = LocalDate.now();
LocalDate lastWeek = now.minusDays(7+now.getDayOfWeek().getValue()-1);
LocalDate currentDate = now.minusDays(now.getDayOfWeek().getValue());
String[] lweek = new String[1];
lweek[0] = String.valueOf(lastWeek);
String lastwk = String.valueOf(lastWeek);
long rv = -1; //<<<< default return to indicate no such row
SQLiteDatabase DB=this.getReadableDatabase();
Cursor cursor=DB.rawQuery("select weather from dailyQuiz1 where date =?",lweek);
if (cursor.moveToFirst()) {
rv = cursor.getLong(cursor.getColumnIndex("weather"));
}
System.out.println(lweek[0]);
System.out.println(rv);
return rv;
}
At the moment, this correctly returns the data week ago in format: 2022-01-31
and returns rv: -1 (which means it can't find the record). However, the record is there in my database:
So realistically I don't want -1 to be returned as I would want the variable in another class I am calling it from to now hold the value of the weather, which you can see in my database is 'Rainy'. Any ideas what I've done wrong or what is a better approach? I feel it will be something so obvious but I've been trying so many things for the past few days :( Thanks for the help
With the exception that you will have an issue with the returned value being 0 if the data is found
i.e. you are getting a long from a text value when using rv = cursor.getLong(cursor.getColumnIndex("weather")) so instead of crashing when trying to convert Rainy to a long 0 is given.
What you have shown works as expected. That leaves the issue to probably be that the database does not in fact contain a row where the date column does equal the String 2022-01-31.
You need to ensure that what is in the actual database being used is as expected (your image appears to be from a tool rather than the actual database and often issues are due to differences).
So in Android Studio run the App and get to a point where it is awaiting for user interaction. The click on App Inspection do you see the same data? e.g. it should look like (not all columns have been included in the example):-
If not then your issue is that the data is not being added as expected and that needs to be corrected.
Otherwise click on the Query Icon
Enter and run SELECT length(date), * FROM dailyquiz1 WHERE date like '2022-01%' e.g. :-
if the first column returned is > 10 then there is an issue with the data that is being stored, as it contains additional data.
if the first column returned is < 10 then you are storing data that is shorter than it should be.
if no data is returned then the data stored is even further away from what it should be.

Using the 'astar' function of OrientDB: an SQL call in Java

I'm using OrientDB to represent large city maps and calculate the shortest traversal times between a pair of nodes when the need arises. I have the following method:
public void getShortestPath(int from, int to){
String query = "SELECT astar(?, ?, time, direction=OUT, customHeuristicFormula=EUCLIDEAN) FROM V";
OResultSet set = db.query(query, getNode(from).getProperty("#rid"), getNode(to).getProperty("#rid"));
}
The getNode(nodeID) method returns the OVertex object present in the database, hence we can identify the #rid. Clearly, this method serves no purpose as is.
My issue comes when trying to call the astar query on the database (i.e. line two of the method). I'm getting the following error: OCommandSQLParsingException: Error parsing query upon reaching the first ( (i.e. error encountering the open bracket). Removing the brackets entirely simply resulted in the same error occurring on the # in front of the first #rid value.
I can't seem to find any example of using this function in practice, and (at least I think) I'm using the function call as suggested by the documentation. Look forward to hearing your thoughts.
I'm using the most recent version of OrientDB: 3.2.3
Turns out the error had nothing to do with the bracket itself. Passing the "direction='OUT'" and "customHeuristicFormula='EUCLIDEAN'" parameters in as part of the string was the problem. The below block did the trick.
String sql = "SELECT ASTAR(" + getNode(from).getProperty("#rid") + ", " + getNode(to).getProperty("#rid") + ", time) FROM V";
try(OResultSet set = db.query(sql, "direction='OUT'", "customHeuristicFormula='EUCLIDEAN'")) {
// some code...
}

Comparing EXTRACT(YEAR FROM table.date) to variable value in IntelliJ IDE

I'm trying to get flight count(rate) per month for particular variable year from my database using following query:
SELECT EXTRACT(MONTH FROM departure_date) AS month, COUNT(*) AS flight_rate
FROM flight
WHERE EXTRACT(YEAR FROM departure_date) = ?
GROUP BY EXTRACT(MONTH FROM departure_date);
Then, I have following Java code:
prepStatement = connection.prepareStatement(query);
prepStatement.setInt(1, Integer.parseInt(yearTxtField.getText()));
The number 1 in prepStatement.setInt(...) keeps being underlined with an error saying:
Cannot resolve query parameter 1
So, my query is obviously wrong.
My question is, how to compare the extracted year in where clause with variable year input from text field, using prepared statement?
EDIT: So, after I've tried to run the code anyway, ignoring IDE underline error, everything works fine and I will get the wanted result. However when I'm trying to run this query alone in intelliJ with right click and execute, I will get an error:
[2016-04-09 02:34:09] [42601] ERROR: syntax error at or near "GROUP"
Position: 135
Not sure if related to that error message, but PostgreSQL's extract function returns a double precision (more here).
So you might want to try setDouble(int parameterIndex, double x) instead of setInt(int parameterIndex, int x).

USing Variables/JAVA functions in SQL arithmetic statements in JAVA Netbeans

I am trying to query my database by using a Java function with another attribute defined in the database. The statement generates no error. However, the output is wrong. The result of the output is null but from my checking it is not null. Please can anyone tell me what I need to do? How can I use JAVA functions in SQl statements?
expired_rows = dbMngr.runQuery(String.format("SELECT ID FROM Student WHERE 'System.currentTimeMillis()' - ArrivalTime > (%s) ", 5000));}
if (expired_rows == null) {
System.out.println("The number of expired row is " + expired_rows);
}
if (expired_rows != null) {
System.out.println("The number of expired row is " + expired_rows.length );
}
You can't use the java function in the way you are trying to. You are just passing the String "'System.currentTimeMillis()'" to the dbms - you want to pass in the result of evaluating that function
Would
"SELECT ID FROM Student WHERE %l - ArrivalTime > (%s) ",System.currentTimeMillis(), 5000));}"
work? ( I'm unsure of the syntax for String.format and don;t have acces to the docs, but hopefully you get the picture ... )
A better solution, but a little further away from the work you have already done, would be to use a PreparedStatement as suggested by GriffeyDog.
Also, if no error is being generated, then it seems a quite likely that your dbMngr class is swallowing the exceptions without reporting them.

Retrieving MySQL time in java

I am running the following query to get time difference of two times
resultSet = statement.executeQuery("SELECT TIMEDIFF('14:03:55.256', '14:02:51.780') AS td");
MySQL gives time difference in this format
00:01:03.476
But both
resultSet.getTime("td"); and resultSet.getObject("td");
returns 00:01:03
According to the documentation getTime(String string) retrieves the value of the designated column in the current row of this ResultSet object as a java.sql.Time object in the Java programming language.
java.sql.Time corresponds to SQL TIME and contains information about hour, minutes, seconds and milliseconds.Then why am I getting 00:01:03 instead of 00:01:03:476?
What I basically want is to store 00:01:03.476 into a String. Is there any workaround or I am doing it wrong?
If you are verifying the result by printing it out note that java.sql.Time.toString() only returns a string in the format hh:mm:ss
You should really use rs.getTimestamp which will return a java.sql.Timestamp
Try to do this:
String s = new SimpleDateFormat("HH.mm.ss.SSS").format(t.getTime());
where t is your variable of type java.sql.Time.
Hope this will solve you problem.

Categories