Inserting date in a database using PreparedStatement in Java - java

I have a form which captures a date that the user input in a JFormattedTextField. Then the Date need to be stored in a database (postgresql) using PreparedStatement. I am having error messages at the line pStat.setDate(4, dob);.
Date dob = (Date)ftxtDOB.getValue();
String add = txtAddress.getText();
String country = txtCountry.getText();
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres", "postgres","cisco");
pStat = conn.prepareStatement("INSERT INTO customer_info VALUES (?,?,?,?,?,?)");
pStat.setString(1, id);
pStat.setString(2, surname);
pStat.setString(3, fName);
pStat.setDate(4, dob);
}catch(Exception e){
}
Edit: I have this error message from the compiler.
no suitable method found for setDate(int,java.util.Date)
method java.sql.PreparedStatement.setDate(int,java.sql.Date,java.util.Calendar) is not applicable
(actual and formal argument lists differ in length)
method java.sql.PreparedStatement.setDate(int,java.sql.Date) is not applicable
(actual argument java.util.Date cannot be converted to java.sql.Date by method invocation conversion)
Edit: SOLVED, I used:
pStat.setDate(4, new java.sql.Date(dob.getTime()));

What error message?
Guessing that it's actually a compiler error message, are you sure you are using java.sql.Date and not java.util.Date?
Edit: As you edited question, yes you will need new java.sql.Date(date.getTime()) or something (data handling in Java is a mess! (at the moment)).

Related

How to insert into JDate chooser value into db

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.

How can i insert value in timestamp datatype column in SQL using java or JSP

I have tried to add value using preparedStatement.
----Some piece of Code----
`
String query = "INSERT INTO COMMENTS VALUES(?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, email);
ps.setString(2, name);
ps.setTimestamp(3, now);
3rd column is timestamp type. But this is showing error.
It shows a whole list of packages needed to be imported. But when i import a package, it asks me to create a variable named 'now'.
Help me, how to fill timestamp field in database using java or JSP.
Thanks in advance
'now' needs to be of type java.sql.Timestamp
you can run a quick test by doing
ps.setTimestamp(3,getCurrentTimeStamp());
where getCurrentTimeStamp() is
public java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
To shorten HocusPocus correct answer even more, maybe
ps.setTimestamp(3, new java.sql.Timestamp(java.lang.System.currentTimeMillis()));

java sql - insert timestamp into sql database

I'm trying to insert a timestamp into a database, but my code throws an exception, which tells me it's something with my sql statement.
The exception message shown is:
"Fout in Rit_ToevoegenController.okKnop(): SQLException in RitDB.voegRitToe() - statement"
okKnop is a different method that calls voegRitToe().
The type of the column called 'starttijd' is TIMESTAMP, and the DB Data type is DateTime.
i'm fairly certain that it's the timestamp that causes problems, because the other 2 are just a String and an int.
Any help with making it work would be greatly appreciated. I need to insert both the time and date into the database for comparing later.
public void voegRitToe(Rit r) throws DBException{
Timestamp starttijd = new Timestamp(System.currentTimeMillis());
//Date date = new Date(starttijd.getTime());
try(Connection conn = ConnectionManager.getConnection();){
try(PreparedStatement stmt = conn.prepareStatement("insert into rit(starttijd, lid_rijksregisternummer, fiets_registratienummer) values(?,?,?)");){
stmt.setTimestamp(1, starttijd);
stmt.setString(2, r.getLid().getRegisterNr());
stmt.setInt(3, r.getFiets().getRegisNr());
stmt.execute();
}
catch(SQLException sqlEx){
throw new DBException("SQLException in RitDB.voegRitToe() - statement");
}
}
catch(SQLException sqlEx){
throw new DBException("SQLException in RitDB.voegRitToe() - verbinding");
}
}
TIMESTAMP and DATETIME serve different purposes; TIMESTAMP is for automatic time stamping.
java.util.Date starttijd = new java.util.Date(System.currentTimeMillis());
java.util.Date starttijd = new java.util.Date(); // Or this
I guess you came at Timestamp, as java.sql.Date wraps java.util.Date by setting the time part to zero!
If the database server's time is correct, one could also do:
... VALUES(NOW(), ?, ?)
By the way, java 8 introduces new date/time classes and "improve" upon the JDBC usage, if you have a java 8 compliant driver.

String found, numeric expected in Oracle function called from Java

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.

"Literal does not match the format string" error

When I try to execute the below code it gives me an java.sql.SQLException: ORA-01861: literal does not match format string error.
I am trying to copy some of the column values from customer1_details table to customer2_details table. The columns datatype which I am trying to move is TIMESTAMP(6) for TIME_REGISTERED, DATE_DISCHARGED columns and the datatype for DATE_OF_BIRTH column is DATE
try
{
Connection conn=Address.getOracleConnection();
int id = 1;
Date dob = null;
Timestamp timereg = null,datedischarged = null;
Statement stmt=conn.createStatement();
ResultSet res=stmt.executeQuery("SELECT TIME_REGISTERED,DATE_DISCHARGED,DATE_OF_BIRTH from customer1_details WHERE customer_id = '"+id+"' ");
if(res.next())
{
timereg=res.getTimestamp("TIME_REGISTERED");
datedischarged=res.getTimestamp("DATE_DISCHARGED");
dob=res.getDate("DATE_OF_BIRTH");
}
String sql1="INSERT INTO customer2_details(TIME_REGISTERED_3,DATE_DISCHARGED_3,DATE_OF_BIRTH,customer_ID) "
+ "VALUES('"+timereg+"','"+datedischarged+"','"+dob+"','"+id+"') ";
PreparedStatement pst=conn.prepareStatement(sql1);
pst.executeUpdate();
pst.close();
conn.close();
}
catch(Exception e)
{ System.out.print(e); }
It will be more helpful if anyone provides the answer without using INSERT INTO ... SELECT ... statement.
YOu can do it in one statement with a query like:
"INSERT INTO customer2_details (TIME_REGISTERED_3,DATE_DISCHARGED_3,DATE_OF_BIRTH,customer_ID)
SELECT TIME_REGISTERED,DATE_DISCHARGED,DATE_OF_BIRTH, customer_id
from customer1_details WHERE customer_id = '"+id+"' "
This is most likely caused by passing your Date and Timestamp variables as Strings to the insert statement.
When you insert or update Date or Timestamp values, there is a default format in which you can pass those values as strings. What you pass is java's idea of how to convert Dates and Timestamps into strings. These two don't seem to match.
Your best bet is probably to use bind variables, then the framework should take care of that.
An Alternative would be to use Oracle's to_date() function, where you can specify the format string. You would then define a format string which considers java's way of representing dates as strings. However, I am not sure if the java representation depends on the locale. If so, you would have to write you own date_to_string() method, which always returns dates in the same format, or your program may work on some computers, but not on others with a different locale.
And finally you can do an insert-select which bypasses the java layer entirely.
Read the timestamps as strings with getString();
OR call toString() in your java Timestamp object instances.
String sql1="INSERT INTO customer2_details(TIME_REGISTERED_3,DATE_DISCHARGED_3,DATE_OF_BIRTH,customer_ID) "
+ "VALUES('"+timereg.toString()+"','"+datedischarged.toString()+"','"+dob.toString()+"','"+id+"') ";

Categories

Resources