I have a table with a column datetime i want to retrieve data from database where date is specified in jdatechooser but em continously getting error:
Cannot make a static reference to the non-static method getDate() from
the type JDateChooser
Here is the code:
public void actionPerformed(ActionEvent e) {
Date date = JDateChooser.getDate();
try{
String query = " Select *from Transactions WHERE "+date+"=? ";
PreparedStatement pst = con.prepareStatement(query);
ResultSet rs = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}catch (Exception e1){
e1.printStackTrace();
}
}
It's theoretically possible to have a window with lots of different JDateChooser controls on it. So when you refer to one of them, you need to specify which one, rather than just calling it JDateChooser.
Somewhere in your class, you'll have a declaration something like
private JDateChooser theChooser;
where you declare a variable to refer to your JDateChooser - that is, you give it a name. Now, you need to use the EXACT SAME NAME when you refer to your JDateChooser in your actionPerformed method. For example
Date date = theChooser.getDate();
But don't write theChooser - write whatever name YOU gave the JDateChooser when you declared the variable.
Related
I am planning to add 'Date' objects into the SQLite database. However, I am getting an error about the insertion being null.
The error is this
org.sqlite.SQLiteException: [SQLITE_CONSTRAINT_NOTNULL] A NOT NULL constraint failed (NOT NULL constraint failed: dates.Tarih)
at org.sqlite.core.DB.newSQLException(DB.java:909)
at org.sqlite.core.DB.newSQLException(DB.java:921)
at org.sqlite.core.DB.execute(DB.java:825)
at org.sqlite.jdbc3.JDBC3PreparedStatement.execute(JDBC3PreparedStatement.java:53)
This is my code. I suspect from the question marks. Because when I remove them and place them with 'now'. It actually works. But, the following code throws the above error.
Insert method
public static void insert(Date date, Date date2) {
try{
System.out.println(" date:"+date.toString());
String query = "insert into dates(Tarih,Tarih2) values(strftime('%d-%m-%Y',?), strftime('%d-%m-%Y',?))";
pst=conn.prepareStatement(query);
pst.setObject(1,date);
pst.setObject(2,date2);
pst.execute();
}catch (SQLException e){
e.printStackTrace();
}
}
Probably you have defined the column Tarih as NOT NULL and your code is trying to insert a null value in the table.
The reason that you get null from strftime() is because you don't pass a valid date for SQLite.
For SQLite valid dates/datetimes are either strings in the format yyyy-MM-dd hh:mm:ss, or integer unix epoch times or floating point numbers representing julian days.
What you pass are Date objects and this is your mistake.
One way to solve the problem is to extract from each of the Date objects an integer representing unix epoch time and pass that to strftime():
public static void insert(Date date, Date date2) {
try{
long d = date.toInstant().toEpochMilli() / 1000;
long d2 = date2.toInstant().toEpochMilli() / 1000;
String query = "insert into dates(Tarih,Tarih2) values(strftime('%d-%m-%Y', ?, 'unixepoch'), strftime('%d-%m-%Y', ?, 'unixepoch'))";
pst=conn.prepareStatement(query);
pst.setLong(1, d);
pst.setLong(2, d2);
pst.execute();
} catch (SQLException e){
e.printStackTrace();
}
}
I have an column defined as datetime(2) and I have to create a new date in this format - 2016-01-01T19:33:15-05:00
Entity: private Date transactionTime;
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS");
Date date = null;
try {
date = formatter.parse(formatter.format(new Date()));
} catch (ParseException e) {
e.printStackTrace();
}
obj.transactionTime(date);
It is getting inserted in SQL as like this - "2021-08-26 14:19:09.0000000" but I need insert this in the format mentioned above.
There is only column type, datetimeoffset that can hold the timezone offset (e.g. -05:00 as mentioned in your question) value. Check the Data type mappings documentation to learn more about it.
So, if you want to store the timezone offset value, change the column type to datetimeoffset. After that, you will be able to insert the value which you have mentioned in the question.
You can use the following code to access the stored value:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT foo FROM mytable WHERE ...");
while (rs.next()) {
DateTimeOffset dateTimeOffset = rs.getObject(1, DateTimeOffset.class));
System.out.println(dateTimeOffset);
}
rs.close();
st.close();
where foo the name of the column of type, datetimeoffset.
The java program contains a table which has two columns, Time & Feed Amount. The contents of the table is obtained from a database using the select query. I wanted to pass the specific Time value being clicked on the column Time to a JSpinner (mouse-click event). The JSpinner was customized to handle Time data types (HH:mm:ss format). I tried some methods but was unable to pass the value to the JSpinner and get the error java.lang.ClassCastException:java.lang.String cannot be cast to java.util.Date. I somehow understand the error, but dont know what methods to use. Codes used are shown below.
EDIT. I was able to do it using getTime method. The intellisense was really helpful.
Mouse Event
private void feedsched_tableMouseClicked(java.awt.event.MouseEvent evt) {
try{
int row = feedsched_table.getSelectedRow();
String table_click=(feedsched_table.getModel().getValueAt(row, 0).toString());
String sql = "SELECT * FROM feedingsched WHERE time='"+table_click+"'";
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
if(rs.next()){
// I GUESS THIS GIVES THE ERROR
Object value = rs.getString("time"); // "time" is the column name from the database
Date date = (Date)value;
SimpleDateFormat format = new SimpleDateFormat("HH:mm:ss");
String timeval = format.format(date);
time_spinner.setValue(timeval);
}
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
Spinner's customized code
Date date = new Date();
SpinnerDateModel sm = new SpinnerDateModel(date, null, null, Calendar.HOUR_OF_DAY);
time_spinner = new javax.swing.JSpinner(sm);
JSpinner.DateEditor te = new JSpinner.DateEditor(time_spinner, "HH:mm:ss");
time_spinner.setEditor(te);
getContentPane().add(time_spinner, new org.netbeans.lib.awtextra.AbsoluteConstraints(20, 150, 140, 30));
Solution
Object value = rs.getTime("time");
time_spinner.setValue(value);
I have a JDateChooser in my form. and I need to insert it's Date value into DB.
I used this method just after "public class Nonacademic extends javax.swing.JInternalFrame {" ,
and the method I used is mentioned below,
public static java.sql.Date convertUtilDateToSqlDate(java.util.Date date){
if(date != null) {
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
return sqlDate;
}
JOptionPane.showMessageDialog(null, "No Dates are Specified!");
return null;
}
and In my Add button's actionPerformed event I used
Connection c=DBconnect.connect();
Statement s = (Statement) c.createStatement();
PreparedStatement statement = c.prepareStatement("INSERT into nonacademic ( empId, name, Dob, JoinedDate) VALUES (?,?,?,?)");
statement.setString(1,txtEmpId.getText());
statement.setString(2, txtNmae.getText());
statement.setDate(3,convertUtilDateToSqlDate( (Date) jDateChooserDOB.getDate()));
statement.setDate(4, convertUtilDateToSqlDate( (Date) jDateChooserDateOfJoined.getDate()));
statement.executeUpdate();
Problem is It is gives this error,
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
When I search for a solution to this, I found that this runtime error happens due to Parent class Instance is casting into child class.So can u give me a suggestion to correct this code.
Note:
After done coding above code when I select a Date in JDateChooser It appears as this 2015-08-06, Before code above stuff It appears as Aug 6,2015.
Try below statements,
statement.setDate(3,convertUtilDateToSqlDate(jDateChooserDOB.getDate()));
statement.setDate(4, convertUtilDateToSqlDate(jDateChooserDateOfJoined.getDate()));
Reason:
This is because of import statements. You might have imported only java.sql.Date or java.sql.* statement in your code. All "Date" class you mentioned in your program will be treated as java.sql.Date. So JVM is trying to converting java.util.Date to java.sql.Date in those statement and throwing exception.
EDIT
Putting this here in case it helps others. My problem was a failure in understanding how PreparedStatement works. I had believed that the "?"...setInt() syntax was a simple substitution that constructs an SQL statement, interprets it and sends that to the DB, which is not the case. The answers below explain in detail the problem.
ORIGINAL QUESTION
I'm having some trouble getting an Oracle package function call to execute from within a Java app. I am receiving the below error:
ORA-01858: a non-numeric character was found where a numeric was expected
I believe I have constructed the call correctly, and the only place I'm using a string is for a date field (not a numeric one). The function has the signature:
function f_get_mr_target(a_plan_id number,a_machine number,a_shift_id number,a_shift_dt date) return number;
My java code invoking the function is as follows:
public Double checkMRTarget(int planId, int machineNum, int shiftId, String date)
{
//Instantiate the return value
Double mrTarget = null;
//Get the MR target
try
{
//Ready the connection
con = nativeDataSource.getConnection();
//The query string
String sql = "select pkg_bcs.f_get_mr_target(?,?,?,?) target from dual";
//Prepare the query
stmt = null;
stmt = con.prepareStatement(sql);
stmt.setInt(1, planId);
stmt.setInt(2, machineNum);
stmt.setInt(3, shiftId);
stmt.setString(4, date);
//Execute the query
ResultSet rs = stmt.executeQuery();
//Extract the value from the result set
mrTarget = rs.getDouble("target");
}
catch (Throwable e)
{
System.out.println("Error getting mrTarget: " + e);
}
finally
{ closeDBConnections(); }
//Return the value
return mrTarget;
}
Con is a public Connection object shared by all other methods in the class. Stmt is a PreparedStatement object, also shared. The parameters are passed as follows:
planId = 986548
machineNum = 5227
shiftId = 10
date = "trunc(sysdate)"
I've verified that running
select pkg_bcs.f_get_mr_target(986548, 5227, 10, trunc(sysdate)) target from dual;
works just fine in SQLDeveloper. As far as I can tell, it's getting a number where it expects a number
You've called setString, so Java sent a String that Oracle can't implicitly convert into a DATE.
You can convert it to a java.sql.Date, java.sql.Time, or java.sql.Timestamp by first parsing the date with a SimpleDateFormat, and creating the appropriate object, and calling setDate, setTime, or setTimestamp instead of setString.
Alternatively, you can get Oracle to convert it by calling to_date in your JDBC SQL:
// Your date format may vary.
String sql = "select pkg_bcs.f_get_mr_target(?,?,?,to_date(?, 'YYYY-MM-DD')) target from dual";
the 4th parameter which is date do not work with String. It waits for a Date object.
Here is your method signature, pass a Date object instead of String.
public Double checkMRTarget(int planId, int machineNum, int shiftId, Date date)
Substituting a string datatype to a Date parameter is a catastrophe. It will surely the ORA-01858 exception in this case (in context of you code).
Parameter substitution demands exact binding which serves its purpose of being strongly typed.
Please convert the fourth parameter i.e. the string parameter into a date object. & then implement what you wish to. It should work fine then.
Also, trunc(sysdate) in SQL query does not return a string to the SQL client. Rather it returns the date(internal conversion). This is designed such that the parser recognize the date type efficiently and consistently.