problem in adding java date in MySQL? - java

here is the code
String DateOfBirth[]=strDOB.split("/");
Date dateOfBirth = new Date();
dateOfBirth.setYear(Integer.parseInt(DateOfBirth[2].trim()));
dateOfBirth.setMonth(Integer.parseInt(DateOfBirth[1].trim()));
dateOfBirth.setDate(Integer.parseInt(DateOfBirth[0].trim()));
java.text.SimpleDateFormat DateFormat = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
strDOB = DateFormat.format(dateOfBirth);
DBProcess.QueryExecuter("INSERT INTO patients(patient_id,first_name,last_name,middle_name,birth_dt) VALUES (\""+Double.parseDouble(strPatientID.trim())+"\",\""+strFirstname+"\",\""+strLastname+"\",\""+strMiddlename+"\",\""+strDOB +"\");");

Oh, my.
See if this is better:
private static final String INSERT_SQL = "insert into patients(patient_id, first_name, last_name, middle_name, birth_dt) values(?, ?, ?, ?, ?)";
DateFormat inputFormatter = new SimpleDateFormat("dd/MM/yy");
Date dob = inputFormatter.parse(strDOB);
PreparedStatement ps = connection.prepareStatement(INSERT_SQL);
// bind your values here.
int numRowsAffected = ps.executeUpdate();
I can't understand why you'd write that code to parse a date string when DateFormat was born to do it. And I certainly hope that your birth_dt column is of type Date in your database. Anything else is utterly foolish.

In your code, do you use java.util.Date or java.sql.Date ?
The best way to insert a Java date in MySQL (or other DB) is to use the PreparedStatement, and the java.sql.Date class :
java.sql.Date theDate = new Date(longTime);
PreparedStatement stmt = conn.prepareStatement("INSERT INTO table(id,date) VALUES (?,?)");
stmt.setInt(1, 123);
stmt.setDate(2, theDate);
stmt.execute();

Related

Date specific format in mysql

Is there any way to store the below date in mysql table
Date = 2017-01-05T00:00:00+05:30
//Table
create table test(dob DATETIME);
//Insert
insert into test(dob) values ('2017-01-05T00:00:00+05:30') // Throws error saying Incorrect datetime
Is there way I can insert the below date in mysql db from java code.
If you have a Date object, good. Otherwise, parse the string into a Date object using SimpleDateFormat like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date d = sdf.parse("2017-01-05T00:00:00+05:30");
Then you can make a PreparedStatement to do the date insert like this:
PreparedStatement ps = conn.prepareStatement("insert into test(dob) values (?)");
ps.setDate(1, new java.sql.Date(d.getTime()));
ps.executeUpdate();

sql delete based on date

I am a total noob to java and sqlite. This should be simple, but I have tried and searched and can't get it to work. I have a date field in SQL that I am formatting as a sql date (MM/dd/yy). I want to delete based on a date passed. For the moment, I am only trying to display rows based on a passed date.
My code to run the query is:
String query = "select * from Peter1Score where DateSort='"+convertSQLDate("09/20/15")+"'";
PreparedStatement pst = connection.prepareStatement(query);
ResultSet rs = pst.executeQuery();
My converSQLDate() is:
public static java.sql.Date convertSQLDate (String sqlDateIn)
{
java.sql.Date returnDate = null;
SimpleDateFormat formatter = new SimpleDateFormat("MM/dd/yy");
Date parsed;
try
{
parsed = formatter.parse(sqlDateIn);
java.sql.Date sqlDate = new java.sql.Date(parsed.getTime());
returnDate = sqlDate;
}
catch (ParseException e)
{
e.printStackTrace();
}
return returnDate;
}
I am passing 09/20/15 just for test. I have a record with that date, but it doesn't get selected.
You're not binding any variables into the statement (using the setXY() methods of PreparedStatement). Instead, you're concatenating a string value (result of Date.toString()) into the query literal.
Try this instead:
String query = "select * from Peter1Score where DateSort=?";
PreparedStatement pst = connection.prepareStatement(query);
pst.setDate(1, convertSQLDate("09/20/15"));

Error when I set parameters to PreparedStatement

I have MSSQL procedure:
my_proc
I get data from java
String sql = "exec my_proc '2016-01-01','2016-01-20','2016-01-01'";
stmt = connection.prepareStatement(sql);
rs = stmt.executeQuery();
and get all data fine!
but if I use
String msisdn, String startDate, String endDate
String sql = "exec my_proc ?,?,?";
stmt = connection.prepareStatement(sql);
stmt.setString(1, msisdn);
stmt.setString(2, startDate);
stmt.setString(3, endDate);
rs = stmt.executeQuery();
I get error:
com.microsoft.sqlserver.jdbc.SQLServerException: Error converting data type varchar to datetime.
In procedure I have variables:
#Startdtin datetime,
#Enddtin datetime,
#msisdnin varchar(18)
I tried use
stmt.setTimestamp(2, startDate); //startDate - convert to Timestamp
and
stmt.setDate(2, startDate); //startDate - convert to Date (sql and util)
It is not helped. How pass date to PreparedStatementcorrectly`?
Your startDate is of type String. So convert it into Date type.
java.util.Date myDate = new java.util.Date(startDate);
java.sql.Date sqlDate = new java.sql.Date(myDate.getTime());
-------------------------------
stmt.setDate(5, sqlDate);
Use CallableStatement to execute procedures.
Once corrected the format of your data you have to change the code.
To execute a procedure you need to use a CallableStatement, not a PreparedStatement.
If you have your date in string format, first convert it to Date in java using a SimpleDateFormat.
Than simply set it as Date on the callableStatement.
String dateString = ...;
Date date = ...;
myCallableStatement.setDate(1, date);

To store a date in mySQL as dd/MM/yyyy format through Netbeans, but mySQL generally takes yyyy/MM/dd

I entered the following codes. my goal is to store a date in mySQL as dd/MM/yyyy format. But mySQL generally takes yyyy/MM/dd.
String d=(((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText());
Statement stmt = db.conn.createStatement();
String sql = "insert into diag.current " +
"values'"+col1+"','"+col2+"','"+java.sql.Date.valueOf(d)+"','"+col4+"')";
stmt.executeUpdate(sql);
I right clicked on the jDateChooser1 and clicked on Customized code, and entered :
jDateChooser1= new com.toedter.calendar.JDateChooser("dd/MM/yyyy","##/##/####",'_');
Now please let me know where i am making the mistake. I will be grateful if someone solves this. Thanks in Advance. I hope i portrayed clearly...
Should be something, like the following. Better list the column names, for future changes to the table, and for readability. A ( got lost in your code. Using a prepared statement escapes strings and prevents SQL injection. For dates, integers and such it is also beneficial.
java.sql.Date date = new java.sql.Date(SimpleDateFormat("dd/MM/yyyy").parse(d).getTime());
PreparedStatement stmt = db.conn.createPreparedStatement();
String sql = "INSERT INTO diag.current (COL1, COL2, COL3, COL4) VALUES(?, ?, ?, ?)";
PreparedStatement stmt = db.conn.createPreparedStatement();`
stmt.setString(1, col1);
stmt.setString(2, col2);
stmt.setDate(3, date);
stmt.setString(4, col4);
stmt.executeUpdate();
stmt.close();
I have edited my program using your help as shown below:
java.sql.Date date = new java.sql.Date(SimpleDateFormatter("dd/MM/yyyy").parse(d).getTime());
PreparedStatement stmt = db.conn.prepareStatement(); 
String sql = "INSERT INTO diag.current (name, patientID, address, sex, phone, vip, email, purpose, history, tests, doc, charges, status, dob, nextapp) " +     
"VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";    
PreparedStatement stmt = db.conn.createPreparedStatement(); 
stmt.setString(1, name);
stmt.setString(2, id);
stmt.setString(3, add);
stmt.setString(4, sex);
stmt.setString(5, ph);
stmt.setString(6, vip);
stmt.setString(7, mail);
stmt.setString(8, pur);
stmt.setString(9, phis);
stmt.setString(10, tests);
stmt.setString(11, dc);
stmt.setInt(12, total);
stmt.setString(13, status);
stmt.setDate(14, date);
stmt.setDate(15, date);
stmt.executeUpdate();
stmt.close();
Q: But SimpleDateFormatter and createPreparedStatement is not supporting, which import I should use?
A: Typos, should have been
java.text.SimpleDateFormat
con.prepareStatement
From the MySQL Manual - 11.3.1. The DATE, DATETIME, and TIMESTAMP Types
The DATE type is used for values with a date part but no time part. MySQL retrieves and displays DATE values in 'YYYY-MM-DD' format. The supported range is '1000-01-01' to '9999-12-31'.
The DATETIME type is used for values that contain both date and time parts. MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format. The supported range is '1000-01-01 00:00:00' to '9999-12-31 23:59:59'.
The TIMESTAMP data type is used for values that contain both date and time parts. TIMESTAMP has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC.
MySQL converts TIMESTAMP values from the current time zone to UTC for storage, and back from UTC to the current time zone for retrieval. (This does not occur for other types such as DATETIME.) By default, the current time zone for each connection is the server's time.
MySQL permits a “relaxed” format for values specified as strings, in which any punctuation character may be used as the delimiter between date parts or time parts. For example YYYY/MM/DD is acceptable as a DATE.
So it appears that you have to create a text date in YYYY-MM-DD format to insert a date into MySQL. When you retrieve a DATE field, you get YYY-MM-DD.
The PreparedStatement is supposed to do this conversion for you from a java.sql.Date when you use the setDate method.
dateChooserDialog1.showDialog(this.getFrame());
Calendar d=dateChooserDialog1.getSelectedDate();
SimpleDateFormat sdf=new SimpleDateFormat("DD-MM-YYYY");
String s=d.toString();
String dd=s;
String mm=s;
String yyyy=s;
int i=dd.lastIndexOf("DAY_OF_MONTH");
dd=dd.substring(i+13,i+16);
dd=dd.substring(0,dd.lastIndexOf(","));
int j=mm.indexOf("MONTH");
mm=mm.substring(j+6,j+9);
mm=mm.substring(0,mm.lastIndexOf(","));
j=Integer.parseInt(mm);
mm=String.valueOf(j+1);
int z=yyyy.indexOf("YEAR");
yyyy=yyyy.substring(z+5,z+10);
yyyy=yyyy.substring(0,yyyy.lastIndexOf(","));
//s.substring(busyIconIndex, busyIconIndex);
String dob=dd+"/"+mm+"/"+yyyy;
DateField.setText(dd+"/"+mm+"/"+yyyy);

How to set current date and time using prepared statement?

I have a column in database having datatype DATETIME. I want to set this column value to current date and time using `PreparedStatement. How do I do that?
Use PreparedStatement#setTimestamp() wherein you pass a java.sql.Timestamp which is constructed with System#currentTimeMillis().
preparedStatement.setTimestamp(index, new Timestamp(System.currentTimeMillis()));
// ...
Alternativaly, if the DB supports it, you could also call a DB specific function to set it with the current timestamp. For example MySQL supports now() for this. E.g.
String sql = "INSERT INTO user (email, creationdate) VALUES (?, now())";
Or if the DB supports it, change the field type to one which automatically sets the insert/update timestamp, such as TIMESTAMP instead of DATETIME in MySQL.
conn = getConnection();
String query = "insert into your_table(id, date_column) values(?, ?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, "0001");
java.sql.Date date = getCurrentDatetime();
pstmt.setDate(2, date);
Where the function getCurrentDatetime() does the following:
public java.sql.Date getCurrentDatetime() {
java.util.Date today = new java.util.Date();
return new java.sql.Date(today.getTime());
}

Categories