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.
Related
I am developing a Java app, as a learning tool for myself mainly, using a java database tutorial, and for some reason, the resultSet update is not actually updating my database.
Details about the project: I am using the Netbeans IDE and connecting to a Derby database with 5 tables (each with between 3 and 6 columns). The database viewer window is supposed to load all of the records into resultSet's and set the text in each blank in the window to those stored records. This process and the buttons to move the cursor to First, Previous, Next, and Last all work perfectly. The part I am currently working on is making the Update button get the text in the blanks and update the records in the database, accordingly.
Now to the problem: the records don't update. When I run the project and change a value, then press Update, the value doesn't revert back to the original value or anything (since I'm not setting the text again in the updateButton method), but when I click next and then previous, the text is back to its original value. Additionally, the values are not updated when I close the application and query the records in the database. I also don't get any exceptions, and Netbeans tells me the build is successful.
Relevant code for the update method (and yes, I'm aware it's probably inefficient, but I'm trying to just get it working before I break it trying to make it look better):
private void btnUpdateRecordActionPerformed(java.awt.event.ActionEvent evt) {
try {
// get text from fields and convert to appropriate data type
// in times
String wakeTime = fieldWakeTime.getText();
Time wakeTimeTm = java.sql.Time.valueOf(wakeTime);
String outTime = fieldOutTime.getText();
Time outTimeTm = java.sql.Time.valueOf(outTime);
String inTime = fieldOutTime.getText();
Time inTimeTm = java.sql.Time.valueOf(inTime);
String sleepTime = fieldOutTime.getText();
Time sleepTimeTm = java.sql.Time.valueOf(sleepTime);
// in weights
String morningPre = fieldPreWeight.getText();
double morningPreDoub = Double.parseDouble(morningPre);
String morningPost = fieldPostWeight.getText();
double morningPostDoub = Double.parseDouble(morningPost);
String nightWeight = FieldNightWeight.getText();
double nightWeightDoub = Double.parseDouble(nightWeight);
// in meals
String fullMeals = fieldFullMeals.getText();
int fullMealsInt = Integer.parseInt(fullMeals);
String snacks = fieldSnacks.getText();
int snacksInt = Integer.parseInt(snacks);
String sodas = fieldSodas.getText();
int sodasInt = Integer.parseInt(sodas);
String alcohol = fieldAlcohol.getText();
double alcoholDoub = Double.parseDouble(alcohol);
String desserts = fieldDesserts.getText();
int dessertsInt = Integer.parseInt(desserts);
// in ratings
String morningMood = fieldMorningMood.getText();
double morningMoodDoub = Double.parseDouble(morningMood);
String nightMood = fieldNightMood.getText();
double nightMoodDoub = Double.parseDouble(nightMood);
String activityRating = fieldActivityRating.getText();
double activityRatingDoub = Double.parseDouble(activityRating);
// uses rs's to update db columns
// in times
rsTimes.updateTime("WAKE_TIME", wakeTimeTm);
rsTimes.updateTime("OUT_TIME", outTimeTm);
rsTimes.updateTime("IN_TIME", inTimeTm);
rsTimes.updateTime("SLEEP_TIME", sleepTimeTm);
// in weights
rsWeights.updateDouble("MORNING_PRE", morningPreDoub);
rsWeights.updateDouble("MORNING_POST", morningPostDoub);
rsWeights.updateDouble("NIGHT_WEIGHT", nightWeightDoub);
// in meals
rsMeals.updateInt("FULL_MEALS", fullMealsInt);
rsMeals.updateInt("SNACKS", snacksInt);
rsMeals.updateInt("SODAS", sodasInt);
rsMeals.updateDouble("ALCOHOL", alcoholDoub);
rsMeals.updateInt("DESSERTS", dessertsInt);
// in ratings
rsRatings.updateDouble("MORNING_MOOD", morningMoodDoub);
rsRatings.updateDouble("NIGHT_MOOD", nightMoodDoub);
rsRatings.updateDouble("ACTIVITY_RATING", activityRatingDoub);
// updates rows
rsTimes.updateRow();
rsRatings.updateRow();
rsWeights.updateRow();
rsMeals.updateRow();
} catch (SQLException err) {
JOptionPane.showMessageDialog(this, err.getMessage());
}
}
When searching out solutions to this problem I've come across a great deal of variations on suggestions to con.setAutoCommit(false); and then commit the changes at the end of the method block, which I have tried, as well as explicitly con.setAutoCommit(true); to see if it wasn't defaulting to that for some reason, neither of which worked. (For reference, I did an earlier version of this app using, following the tutorial much more closely and using just 1 of the resultSet's and 1 of my tables and was able to get the update button working.) Also, my prepared statements have the resultSet's set to TYPE_SCROLL_INSENSITIVE and CONCUR_UPDATABLE, which I believe to be the correct options.
Link to the github repository of the project: link. The relevant file is MetrikaViewer.java, not DataManip.java, and the README (if you happened to need more information I didn't give you or like self-deprecating snark) is in the master branch, which is not where the rest of the code is (the Metrika branch) because of some problems I had using git (with an almost 100% chance of being caused by my own stupidity).
Really, as a still very new Java learner, I would not be at all surprised if this was caused by some weird misunderstanding of how something works on my part, but after a week of scratching my head, I just can't seem to find it.
Edit: As per Axel, I added updateRow's to the method. Now the changes update within the app while running, but it does not update the database. (I've updated the code above, accordingly, and the github repo should reflect the changes made.)
I have never used these updateXXX() methods, but as I understand the documentation, you have to issue a call to either rs.updateRow() or rs.insertRow() after updating the columns.
Also, you have to make sure to create your statement with ResultSet.CONCUR_UPDATABLE (since by default, readonly is used).
I have an SQL which looks into a dimension table (which stores every dates until year 2020) and then shall retrieve the todays row.
I watched into the table, todays date is in there.
The problem is, that SQL does not return any result.
I am thinking of a problem related to the use of java.sql.PreparedStatement.setDate method.
In past i think this was working fine, now I did some kine of regression test and it failed. The differences to the past are having Oracle 12 DB now instead of 11 in past and running it on CentOS 6.5 instead of AIX.
On search I found this topic here:
Using setDate in PreparedStatement
As far as I can see, I am doing as suggested.
Heres the java code and the query:
public static String SELECT_DATUM = "SELECT TIME_ID, DATE, DAY_NAME, WEEK_NAME, MONTH_NAME, YEAR_NAME, SORTING, RELATIONDATE, VALID_TO, VALID_FROM FROM DIM_TIME WHERE DATE = :date";
java.util.Calendar now = Calendar.getInstance();
now.clear(Calendar.HOUR);
now.clear(Calendar.MINUTE);
now.clear(Calendar.SECOND);
now.clear(Calendar.MILLISECOND);
Date tmpDate = now.getTime();
Date tmpDate2 = new Date(((java.util.Date)tmpDate ).getTime());
statement.setDate(1, tmpDate2 );
I notice that getTime() is called twice. But I dont think its that bad.
I also noticed some displaying formats:
in Database the date-colums shows me the date like this: '08.11.2015'
in java while debugging tmpDate2 shows me a date like this: '2015-11-08'
in java while debugging tmpDate shows me a date like this 'Sun Nov 08 12:00:00 CET 2015'
But again, these are just display formattings while it is a dateobject in background and a date-type in database. I would expect that je JDBC driver would map this itself without formattings, that why we are using setDate method and not setString.
What am I doing wrong? What could I do for further debugging to get it?
I would like see the resulting SQL query which is finally executed with the parameter.
I tried this sql on db isntance:
SELECT * FROM v$sql s WHERE s.sql_text LIKE '%select time%' ;
but only getting this then: "... where date = trunc(:1 )"
On this row at least I can see that it was using the right schema I expected it to use and where I checked whether todays date is available.
Edit:
something I found out:
I saw another code using the same function but giving an GregorianCalendar instead Calendar. When using
new GregorienCalandar();
instead of
Calendar.getInstance();
Theres no difference.
But when I assign a date and dont let the system take the current time, then it works:
Using
new GregorianCalendar(2015, Calendar.NOVEMBER, 8);
Would retrieve the row I want from SQL.
Zsigmond Lőrinczy posted this answer as comment:
Try this: SELECT TIME_ID, DATE, DAY_NAME, WEEK_NAME, MONTH_NAME,
YEAR_NAME, SORTING, RELATIONDATE, VALID_TO, VALID_FROM FROM DIM_TIME
WHERE DATE = TRUNC (:date) – 3 hours ago
This works for my problem.
I am writing this as reponse to check it later as answer on this question if hes not going to write his own response (to get the reputation-points).
But I am wondering how I could get the same by preparing on java.
The code uses the clear-methods, which where released into an own method named 'trunc'. I think the programmer intendet to do this instead of TRUNC in SQL. I am wondering if it werent possible to do so in java and if yes, how?
Edit:
And I am wondering why a TRUNC is needed at all. Because the column in Database is of type Date an not Timestampt. So wouldnt there be an automatically trunc? I would expect this. Why do I need a trunc on SQL?
i saved all my indexed notes documents to Solr server,
so my problem is if any of my notes document is change in my .nsf database. i have to update my notes documents on Solr server.
for that i have to get last modified documents from particular time means i will provide a time as parameter then from that time i should get modified documents.
i searched about it but not getting clear idea about it to initiate my work .
it would be nice if anyone guide me .
If your plan is to get every documents modified since a certain date/time, the best way would be to use the search function on the Database class.
Specify Select #All to get every documents of the database and set the last time you indexed as the second parameter. This way, Domino will get you every documents created or modified since this time.
DateTime dt
A start date. The method searches only documents created or modified since the start date. Can be null to indicate no start date.
Here a small example :
Session session = getSession();
Database db = session.getCurrentDatabase();
Document profile = db.getProfileDocument("solrIndexer","nameOfTheDatabase");
Item lastTimeIndexedItem = profile.getFirstItem("lastTimeYouIndexed");
DateTime lastTimeIndexed = lastTimeIndexedItem.getDateTimeValue();
DocumentCollection col = db.search("Select #All", lastTimeIndexed);
// (Your code goes here)
I have a column in my table with timestamp datatype and the value for instance look like '2014-08-30 00:00:50'. From database point of view I know it's showing the time of 12:00:50 AM for '00:00:50' and 12:00:50 PM if the value is 2014-03-30 12:00:50. But When I process the data in my application by fetching the table values, I'm getting AM for the time which has to be PM. I want to know how could I achieve this? I also want to know that the problem weather it is from my application side ? or database side? Could I achieve this If I get time from database as unixtimestamp format?
I've seen several questions related to this but I found none of them led me to solve this issue. Please help
If you are getting the date as a string you can do the following to convert it to AM/PM.
String s = "2014-08-30 00:00:50";
SimpleDateFormat d = new SimpleDateFormat("y-MM-dd H:mm:s");
Date in24HrFormat = d.parse(s);
String in12HrFormat = new SimpleDateFormat("y-MM-dd h:mm:sa").format(in24HrFormat);
System.out.println(in12HrFormat);
I'm trying to select records by date from a Lotus Notes database and have run into trouble with correctly formatting the date.
Here's the relevant code:
public void runNotes() {
Session s;
try {
s = NotesFactory.createSession((String)null, (String)null, "mypassword");
Database hkDB =
s.getDatabase("NBHDH001/YNM", "H\\DHH00001.nsf", false);
DocumentCollection docs = hkDB.search("[Date]>[2012/03/20]");
Date is a field in the record, and when I looked up records (with FTSearch), the date came back in the format above: [yyyy/mm/dd].
The parameter of the search is what I need here.
i.e. what should I put instead of "[Date]>[2012/03/20]"
I tried various constructions with Calendar and DateFormat, but it's not coming together...
Any suggestions?
You should get rid of the square brackets on the field name. The search method expects a Notes Formula, like what you'd put into a view selection formula:
"Date > [03/20/2012]"
It might also be required that dates are in mm/dd/yyyy format, though if you are in a non-US locale I'm not 100% sure.
You mentioned that you have been doing full text searches in the database, so it is definitely worth mentioning this... If the database actually has a full text index, then you may want to consider using the NotesDatabase.FTSearch() method instead of NotesDatabase.Search(). The FTSearch method will be considerably faster for a large database.
The syntax for FTSearch is different from the syntax for Search. You could use either "FIELD Date > 03/20/2012" or "[Date] > 03/20/2012".