UCanAccess Java Execution Error - java

When attempting to get details from an MS Access database using the following code:
//returns the details of a specific employee for use in the update GUI
public static String getEmployeeDetails(int empID) throws SQLException{
String employee = "";
Statement stmt = conn.createStatement();
String query = "SELECT employeetbl.Department, "
+ "employeetbl.Surname, "
+ "employeetbl.FirstName, "
+ "employeetbl.CurrentPosition, "
+ "FORMAT(employeetbl.DateOfBirth, 'yyyy/mm/dd') AS DateOfBirth, "
+ "employeetbl.TotalYearsRelevantExperience, "
+ "employeetbl.HighestQualification, "
+ "employeetbl.EmailAddress, "
+ "employeetbl.PhoneNo, "
+ "FORMAT(employeetbl.DateOfEmployment, 'yyyy/mm/dd') AS DateOfEmployment "
+ "FROM employeetbl WHERE EmployeeID = "+empID+";";
ResultSet rs = stmt.executeQuery(query);
while(rs.next()){
employee = rs.getString("Department")
+"#"+rs.getString("Surname")
+"#"+rs.getString("FirstName")
+"#"+rs.getString("CurrentPosition")
+"#"+rs.getString("DateOfBirth")
+"#"+rs.getString("TotalYearsRelevantExperience")
+"#"+rs.getString("HighestQualification")
+"#"+rs.getString("EmailAddress")
+"#"+rs.getString("PhoneNo")
+"#"+rs.getString("DateOfEmployment");
}
return employee;
}
called from this method:
if(cmbTable.getSelectedItem().equals("Employees")){
String[] tmp = cmbRecord.getSelectedItem().toString().split("-");
int empID = Integer.parseInt(tmp[0]);
String employeeDetails = Master.getEmployeeDetails(empID);
String[] employee = employeeDetails.split("#");
cmbDepartment.setSelectedItem(employee[0]);
txtSurname.setText(employee[1]);
txtFirstName.setText(employee[2]);
txtCurrentPos.setText(employee[3]);
txtDOB.setText(employee[4]);
txtExperience.setText(employee[5]);
txtQualification.setText(employee[6]);
txtEmail.setText(employee[7]);
txtPhone.setText(employee[8]);
txtEmployment.setText(employee[9]);
}
I am met with the following error
error: net.ucanaccess.jdbc.UcanaccessSQLException: UCAExc:::3.0.0 Java execution: FORMAT
I have no idea what is causing this error since the SQL works perfectly fine when executed in Access and the format is needed otherwise it outputs the records information including the time which is not set or used.

I'd remove the FORMAT from your SQL string and format the date in Java. I do not know what the format of the date is being returned as, but this should allow you to parse it and then input the fields in the Calendar.set() method as shown here:
public static void main(String[] args) {
final Calendar calendar = Calendar.getInstance();
calendar.set(2015, Calendar.AUGUST, 21, 9, 27);
final Date date = calendar.getTime();
final String formattedDate = new SimpleDateFormat("yyyy/MM/dd").format(date);
System.out.println("formattedDate = " + formattedDate);
}

For future readers: the format function is implemented in ucanaccess and the code originally posted is correct. So the following code runs fine with ucanaccess:
select format(#2001-03-02#, 'yyyy/mm/dd') from dual.
Nevertheless there is a lack in the handling of null arguments, which likely causes the issue. So
select format(null, 'yyyy/mm/dd') from dual; causes an exception to be thrown.
Even if I fixed this issue, a casting of the null values to timestamp would be needed using a specific hsqldb syntax, because of the ambiguity with the function FORMAT(varchar,varchar) and FORMAT(double,varchar).
So I suggest this (simplified) workaround:
select nvl2(employeetbl.DateOfBirth,FORMAT(employeetbl.DateOfBirth, 'yyyy/mm/dd'),null) AS DateOfBirth from ...
Notice that, as well as in access, mm means month (and not minutes).

Related

I can not use java.sql.date in java program correctly, it seems like there are some problems at the result set

String content = "SELECT * FROM " + "floor" + floor + " WHERE Roomnumber ='" + roomresult + "'";
System.out.println("next query->" + content);
statement.execute(content);
ResultSet rs = statement.getResultSet();
Date u = rs.getDate("CheckIn");
I want to transform the java.sql.date into java.util.date. I think the
final sentence is correct , but the java told me that there is a
NullPointerExceptio
if u want convert java.sql.date to java.util.date, use :
new java.util.Date(rs.getDate("CheckIn").getTime())
NullPointerException , may be CheckIn cloum not exist, or it be null;
pleas make sure CehckIn field exist and is not be null;

how to load data from mysql using in between two dates

In the code below using java, I am trying to get data from mysql between two choosed dates and load it into table jTable1 but the problem is when I run the data loads correctly but not until the second date.
For example, if first date is 2020-1-1 and second date is 2020-1-31 the data loads from the day of 1 to the day of 30 not until the day of 31. The last day is missing! And if I choose dates from 2020-01-01 to 2020-02-01 it loads from 2020-01-01 to 2020-01-31.
java.sql.Timestamp timestamp = new java.sql.Timestamp(jDateChooser5.getDate().getTime());
java.sql.Timestamp timestamp2 = new java.sql.Timestamp(jDateChooser6.getDate().getTime());
String sql2 = "SELECT sum(`msareffishmarket`.`Amount` ) FROM `manfz`.`msareffishmarket` \n"
+ "Where `msareffishmarket`.`place` = 'محل الأسماك' And ( `msareffishmarket`.`MsarefDate` between '" + timestamp + "' And '" + timestamp2 + "' ) "
+ " group by DATE(`msareffishmarket`.`MsarefDate`)";
stm2 = conn.prepareStatement(sql2);
rs2 = stm2.executeQuery(sql2);
// JOptionPane.showMessageDialog(this, rs.getDouble(4));
jTable3.setModel(DbUtils.resultSetToTableModel(rs2));
You are using your prepared statement incorrectly (though you are correct to think to use one). Consider this version of your code:
String sql = "SELECT MsarefDate, SUM(Amount) AS total FROM manfz.msareffishmarket ";
sql += "WHERE place = 'محل الأسماك' AND MsarefDate BETWEEN ? AND ? GROUP BY MsarefDate";
stm2 = conn.prepareStatement(sql);
stm2.setTimestamp(1, timestamp);
stm2.setTimestamp(2, timestamp2);
rs2 = stm2.executeQuery(); // do not pass the query string here
Edit:
Per the correct observations of #mangusta (see below), you should be using a date/timestamp range to search for your records. Assuming you wanted all records from January 2020, you should be using:
WHERE MsarefDate >= '2020-01-01' AND MsarefDate < '2020-02-01'

Fetching SQLite Data Using Order By DateTime But Not Work

I want to Get All data (Date and time wise) but it's not helpful for me AND also Don't Show any error
Follow this Below links But It's Not Helpful For Me :
android sqlite orderby datetime always fetches 1st row
Order By datetime column SQLite
Why is the ORDER BY not working in a Sqlite query
Insert Record in to SQLite database :
private String getDateTime() {
SimpleDateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy hh:mm a");
Date date = new Date();
return dateFormat.format(date);
}
public long insertCompany(Company company){
//String sql = null;
SQLiteDatabase db = dbHelper.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(DatabaseHelper.KEY_COMPANY_NAME, company.getName());
values.put(DatabaseHelper.KEY_CREATED_AT, getDateTime());
values.put(DatabaseHelper.KEY_COMPANY_WEBSITE,company.getWebsite());
values.put(DatabaseHelper.KEY_COMPANY_EMAIL,company.getEmail());
values.put(DatabaseHelper.KEY_COMPANY_PHONE_HOME,company.getPhoneHome());
values.put(DatabaseHelper.KEY_COMPANY_PHONE_PRIMARY,company.getPhonePrimary());
values.put(DatabaseHelper.KEY_COMPANY_ADDRESS,company.getAddressLine1());
long company_id = db.insert(COMPANY, null, values);
return company_id;
}
Below Code is i'll implement in my Database but It's can't work :
List<Company> companyList = new ArrayList<Company>();
String selectQuery = "SELECT * FROM " + COMPANY + " ORDER BY (" + KEY_CREATED_AT + ") ";
Log.e(TAG, selectQuery);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
Full Code :
public List<Company> getAllCompany(){
List<Company> companyList = new ArrayList<Company>();
String selectQuery = "SELECT * FROM " + COMPANY + " ORDER BY (" + KEY_CREATED_AT + ") ";
Log.e(TAG, selectQuery);
SQLiteDatabase db = dbHelper.getReadableDatabase();
Cursor c = db.rawQuery(selectQuery, null);
if (c.moveToFirst()) {
do {
Company com = new Company();
com.setId(c.getInt(c.getColumnIndex(KEY_ID)));
com.setName(c.getString(c.getColumnIndex(KEY_COMPANY_NAME)));
com.setWebsite(c.getString(c.getColumnIndex(KEY_COMPANY_WEBSITE)));
com.setEmail(c.getString(c.getColumnIndex(KEY_COMPANY_EMAIL)));
com.setPhoneHome(c.getString(c.getColumnIndex(KEY_COMPANY_PHONE_HOME)));
com.setPhonePrimary(c.getString(c.getColumnIndex(KEY_COMPANY_PHONE_PRIMARY)));
com.setAddressLine1(c.getString(c.getColumnIndex(KEY_COMPANY_ADDRESS)));
com.setDate(c.getString(c.getColumnIndex(KEY_CREATED_AT)));
//com.setDate(c.getString(c.getColumnIndex(KEY_UPDATED_AT)));
companyList.add(com);
} while (c.moveToNext());
}
return companyList;
}
See Below Image For Batter understanding Data was not show in Date and Time wise :
Help me :)
Thanks in Advance
VARCHAR not working for date while sorting data. You can insert milliseconds in database and format date while show in View.
replace this line in insertCompany Method.
values.put(DatabaseHelper.KEY_CREATED_AT, System.currentTimeMillis());
replace this line while getting data from DB.
long time = Long.parseLong(c.getString(c.getColumnIndex(KEY_CREATED_AT)));
com.setDate(getFromatDate(time));
Method for format data from Milliseconds.
public String getFromatDate(long dateTime) {
String formatedDate;
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(dateTime);
Date mDate = calendar.getTime();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm a", new Locale("en"));
formatedDate = sdf.format(mDate);
return formatedDate;
}
also u can add DESC at end of your Query See below code:
String selectQuery = "SELECT * FROM " + COMPANY + " ORDER BY (" + KEY_CREATED_AT + ") DESC " ;
Here is full implementation example.
If KEY_CREATED_AT is a char or varchar and not a date otherwise you can simply use order by clause that would be fine.
You can use CONVERT to change the values to a date and sort by that
SELECT *
FROM
COMPANY
ORDER BY
CONVERT(DateTime, KEY_CREATED_AT ,101) DESC
The problem with that is, as Sparky points out in the comments, if KEY_CREATED_AT has a value that can't be converted to a date the query won't execute.
This means you should either exclude the bad rows or let the bad rows go to the bottom of the results
To exclude the bad rows just add WHERE IsDate(KEY_CREATED_AT ) = 1
To let let the bad dates go to the bottom you need to use CASE
e.g.
ORDER BY
CASE
WHEN IsDate(KEY_CREATED_AT) = 1 THEN CONVERT(DateTime,KEY_CREATED_AT,101)
ELSE null
END DESC
You are missing the 'order' to your query in order by clause
String selectQuery = "SELECT * FROM " + COMPANY + " ORDER BY (" + KEY_CREATED_AT + " DESC)";
You can use either ASC or DESC as per required behavior.

Sqlite and setting it between dates, Format Correct but still not working

So I'm trying to get a basic sql string to work where it will grab the records in the sqlite database based on between dates. However, for some reason, it doesn't work. I just don't understand why.
private void viewTransactionsBetweenDatesTable(){
//Sets the table to view transactions between certain dates
try{
//Get's the dates from startDateChooserTransactions1 and endDateChooserTransactions1
DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
DateFormat df2 = new SimpleDateFormat("MMM dd, yyyy");
Date sdct = startDateChooserTransactions1.getDate();
Date edct = endDateChooserTransactions1.getDate();
String sdcts = df.format(sdct);
String edcts = df.format(edct);
String sdctlabel = df2.format(sdct);
String edctlabel = df2.format(edct);
//Child's ID
String cid = childIDCheck1.getText();
//Grab's the specified data and places that as the table
String sql = "SELECT * FROM ChildrenPayment WHERE ChildID='"+cid+"' AND strftime('%Y-%m-%d', 'Report Transaction Date') BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
pst = conn.prepareStatement(sql);
rs = pst.executeQuery();
//Sets up the table
Info1.setModel(DbUtils.resultSetToTableModel(rs));
TableColumnModel tcm = Info1.getColumnModel();
//tcm.removeColumn(tcm.getColumn(3));
// tcm.removeColumn(tcm.getColumn(3));
// tcm.removeColumn(tcm.getColumn(10));
// tcm.moveColumn(11, 10);
// tcm.removeColum(tcm.getColumn(13));
//Changes modLabel1
modLabel1.setText(firstNameEditClass1.getText() + " " + lastNameEditClass1.getText() + " Between " + sdctlabel + " - " + edctlabel);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}finally{
try{
pst.close();
rs.close();
}catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
}
I am using a jdatechooser so I am sort of forced to use SimpleDateFormat compared to the better DateTimeFormatter. Anyway, I'm formatting it according to YYYY-MM-DD like sqlite likes, but when I run the function, the table does not display anything. I set the days pretty wide (Feb 01, 2018 to Feb 14, 2018) and the date in my database is Feb 07, 2018. I have a few records in the database for it to pull. However, it just doesn't do it. And no error is popping up, so I do not know why it is not working.
Image of the records that I'm trying to place into my jtable
Edit1: Before I forget, I also tried the following SQL string
String sql = "SELECT * FROM ChildrenPayment WHERE ChildID='"+cid+"' AND 'Report Transaction Date' BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
This will not work:
strftime('%Y-%m-%d', 'Report Transaction Date')
because the format specifiers you have provided require that you supply three values, one each for year, month, and day.
If the dates in the database are stored as complete SQLite datetime strings, you will have to use
"... date([Report Transaction Date]) BETWEEN '"+sdcts+"' AND '"+edcts+"' ";
Note square brackets (not single quotes) around column name. This has nothing to do with needing a date/time value, it's because the column name has spaces in it. Any column name with spaces has to be enclosed in double quotes or square brackets. That's why it's a good idea to never use spaces in column names.
If they are, in fact, stored as 'YYYY-MM-DD' strings, then the reason your alternative didn't work is because you single-quoted the column name 'Report Transaction Date', which results in comparing that literal string to the date values.

Conversion failed when converting date and/or time from character string SQL Server 2016

Hello so i have a these code that have you enter a year, a month, a day all string into a text field and then it will combine them to make one string and used a statement to make query convert this to date and inserting it and some other data into a database here is the code.
int CustomerID = Integer.parseInt(txtCustomerID.getText());
int CarID = Integer.parseInt(txtCarID.getText());
String startdateyear = txtStartDateYear.getText();
String startdatemonth = txtStartDateMonth.getText();
String startdateday = txtStartDateDay.getText();
String enddateyear = txtEndDateYear.getText();
String enddatemonth = txtEndDateMonth.getText();
String enddateday = txtEndDateDay.getText();
String StartDate = startdateyear + startdatemonth + startdateday;
String EndDate = enddateyear + enddatemonth + enddateday;
int HiringPrice = Integer.parseInt(txtHiringPrice.getText());
String Pay = txtPay.getText();
carDA.insert(CustomerID, CarID, StartDate, EndDate, HiringPrice, Pay);/
This is the Insert Query:
stm.executeUpdate("INSERT INTO CarOrder VALUES (" + CarID +"," + CustomerID +",CONVERT(DATE," + "'" +StartDate+ "', 111), CONVERT(DATE," + "'" +EndDate+"', 111)," +HiringPrice+ "," +"'"+Pay+ "')");
When i run the program it throws this message:
Conversion failed when converting date and/or time from character string.
I cant seem to find out why it is doing this, if any one can help me i will be thankful.
It seems that the date format you enter is not correct is should look like :
convert(datetime, '2017/06/24', 111) -- yyyy/mm/dd
because you are using the 111 so your input should look like yyyy/mm/dd, read more about this CAST and CONVERT (Transact-SQL)
To avoid syntax error or SQL Inject i suggect to use PreparedStatement instead, it is more helpful and more secure.
DateFormat format = new SimpleDateFormat("yyyy/mm/dd");
String query = "INSERT INTO CarOrder VALUES (?, ?, CONVERT(DATE, ?, 111), CONVERT(DATE, ?, 111), ?, ?)";
try (PreparedStatement insert = connection.prepareStatement(query)) {
insert.setInt(1, CustomerID);
insert.setDate(2, new Date);
insert.setDate(3, format.parse(StartDate));
insert.setDate(4, format.parse(EndDate));
insert.setDouble(5, HiringPrice);//i think the price is a double maybe you make it int or float so you have to use the right type
insert.setString(6, Pay);
insert.executeUpdate();
}
You are getting invalid string here:
String StartDate = startdateyear + startdatemonth + startdateday;
For example, startdateyear = '2016', startdatemonth = '4', startdateday = '1' --> StartDate = '201641' --> select CONVERT(DATE,'201641', 111) -->
Msg 241, Level 16, State 1, Line 1 Conversion failed when converting
date and/or time from character string.
Why on the earth do you use 111 format that is yy/mm/dd while your string does not contain / at all? That '201641' is interpreted like year=2020, month=16, day=41

Categories

Resources