Inserting date into MySQL database using a PreparedStatement - java

I want to update the string date into MySQL database using prepared statement. I have tried a lot and always got error java.util.Date cannot parse into java.sql.Date or vise versa. I didn't import anything here. Please import according to your answer.
public class Date1
{
public static void main(String args[])
{
String source="2008/4/5";
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
java.sql.Date d=(Date) format.parse(source);
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/employee", "root", "root");
PreparedStatement ps=con.prepareStatement("insert into ankur1 values(?)");
ps.setDate(1,(java.sql.Date) d);
ps.executUpdate();
}
}

Write this
java.sql.Date d= new java.sql.Date(format.parse(source).getTime());
instead of this:
java.sql.Date d=(Date) format.parse(source);
Because you cannot just cast java.util.Date to its subtype java.sql.Date. You have to convert it. Do also note that your format string doesn't match your actual date format, as Bill the Lizard commented.

java.sql.Timestamp date = new java.sql.Timestamp(new java.util.Date().getTime());
pstmt.setTimestamp(1, date);
Try this it may work.. Thanks

here is another simpler way to solve this:
preparedStatement = connect.prepareStatement("INSERT INTO test.TABLENAME VALUES (default, STR_TO_DATE( ?, '%m/%d/%Y'), STR_TO_DATE(?, '%l:%i %p'),?,?,?,?,?)");
Or, you can replace the "?" with real data.
This is how I insert date and time to mySQL, just figured it out.
We can adjust the kinds of parameters to meet our data's format, it's easy and clean.

Related

Eliminate time value from date field and change the format while fetching data from database

My program fetches few columns from Access database and displays the data in JTable. It works fine but I need to make some changes while data display. Like, in spite of storing the data in the form of dd-MM-yyyy in Access databse, it displays in the form yyyy-MM-dd tt:tt:tt format while retrieving. I need to display in the form of dd-MM-yyyy in the table. This date field is represented in the 1st column of table as for_date.
sql = "Select for_date as FOR_DATE,outage_time as OUTAGE_TIME,stat_detail as STATION_DETAILS from " + table_sel + " where for_date='" + date1 + "' and stat_detail ='" + combo_sel + "'";
Connection con = null;
Statement st = null;
ResultSet rs = null;
PreparedStatement pst = null;
String dbURL = "jdbc:ucanaccess://C:\\Users\\Dell_PC\\Documents\\SYSTEM_OUTAGE_REPORT.accdb";
con = DriverManager.getConnection(dbURL);
st = con.createStatement();
pst = con.prepareStatement(sql);
rs = pst.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
con.close();
I am being a bit vague here because I have no experience with UCanAccess JDBC driver. As I understand, you are using this. However, I believe that this thread of answers is not complete as long as no one has mentioned the modern way of solving this task. The modern way involves minimizing the use of the outdated class Date, dropping it completely if you can, and using java.time.LocalDate instead.
So the first step is to check whether a new version of UCanAccess conforms with JDBC 4.2. If so, it can directly give you a LocalDate object instead of a Date object. So I’ve read. If this is not an option, first thing after you got hold of your Date is to convert it with yourDate.toLocalDate(). This ought to be the job of your DbUtils.resultSetToTableModel(). However I am not sure whether this is your own method for you to modify or a method in some standard library.
With a LocalDate we’re almost there. This will default display as yyyy-MM-dd. You wanted it the other way around, dd-MM-yyyy. For this, I tend to agree with Robin and camickr that you should use a table renderer. Your renderer should use a
private static final DateTimeFormatter dateFormatter
= DateTimeFormatter.ofPattern("dd-MM-uuuu");
To format your LocalDate it would do
yourLocalDate.format(dateFormatter);
or if you have not had a chance to convert a Date yet, then of course
yourDate.toLocalDate().format(dateFormatter);
You can format the date when retrieving it:
Select Format(for_date, 'dd/mm/yyyy') as FOR_DATE,outage_time as OUTAGE_TIME,stat_detail as STATION_DETAILS from " + table_sel + " where for_date='" + date1 + "' and stat_detail ='" + combo_sel + "'"
You can replace the TableCellRenderer for that column using the JTable#setDefaultRenderer. For formatting your dates in your renderer, you can use a SimpleDateFormat
Can you try with simple date format to change one format to another
String date_s = "2011-01-18 00:00:00.0";
SimpleDateFormat dt = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date = dt.parse(date_s);
SimpleDateFormat dt1 = new SimpleDateFormat("yyyy-MM-dd");
System.out.println(dt1.format(date));
You need to provide a custom renderer to format the date. Read the section from the Swing tutorial on Concepts: Editors and Renderers for basic information on using a renderer with a table.
A basic renderer would be:
public class YMDRenderer extends DefaultTableCellRenderer
{
private Format formatter = new SimpleDateFormat("yy/MM/dd");
public void setValue(Object value)
{
// Format the Object before setting its value in the renderer
try
{
if (value != null)
value = formatter.format(value);
}
catch(IllegalArgumentException e) {}
super.setValue(value);
}
}
Also, Check out Table Format Renderers for reusable classes that allow you to easily date, time, number just by providing a FormatRenderer.

How to update date in Date format to a resultset?

Date dateformat=null;
Date i5Date=null;
SimpleDateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
String date = i5t1.getText();
i5Date=(Date) formatter.parse(date);
while(rs.next())
{
rs.moveToInsertRow();
rs.updateDate("Date",i5Date);
rs.insertRow();
}
This doesnt update the resultset in date format. May i know what changes i have to make to update the resultset in date format. (Note : - I dont want to update in string format.)
Note: - i have made the connections and the resultset is opened.
The date in result set is a java.sql.Date type. You are trying to format java.util.Date.
You need to convert between them to get this to work assuming you are just rendering the date.
If not you need to make the change directly to your schema. See these SO posts:
ResultSet.getTimestamp("date") vs ResultSet.getTimestamp("date", Calendar.getInstance(tz))
java.util.Date vs java.sql.Date
Update
To retrieve between dates like you are trying to do, you need to do:
Connection conn = null;
PreparedStatement pstmt = null;
conn = getConnection();
String query = "select * from table_name between ? and ?";
pstmt = conn.prepareStatement(query);
pstmt.setDate(1, new java.sql.Date(startDate.getTime()));
pstmt.setDate(2, new java.sql.Date(endDate.getTime()));
ResultSet resultSet = pstmt.executeQuery();

Java: java.util.date cannot be cast to java.sql.Time [duplicate]

This question already has answers here:
Merge java.util.date with java.sql.Time
(7 answers)
Closed 9 years ago.
I have time converted from millis and now i would like to make an SQL Insert with that time value. I tried this but it is not working:
String INSERT_RECORD ="INSERT INTO PRAVIDLA (CAS,DEN,MIESTNOST,STAV) values(?,?,?,?)";
PreparedStatement pstmt = con.prepareStatement(INSERT_RECORD);
Calendar calendar1 = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
calendar1.setTimeInMillis(milli);
Time Cas2 = (Time) calendar1.getTime();
pstmt.setTime(1, Cas2);
pstmt.setInt(2, DEN);
pstmt.setString(3, MIESTNOST);
pstmt.setString(4, STAV);
pstmt.executeUpdate();
Any suggestions please?
java.sql.Time extends java.util.Date, so you cannot simply cast it.
You can try something like this:
Time time = new Time(date.getTime());
The following is what I did when I had a similar problem.
java.util.Date utilDate = new java.util.Date("mm/dd/yyyy");
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
Substitute a real date for "mm/dd/yyyy"
calendar1.getTime() returns a Date object, and Time is a sub-class of Date, so a Date cannot be cast into a Time. You can try this instead:
Time Cas2 = new Time(calendar1.getTimeInMillis());
You can try this. I've not tested the code.
Time time = new Time(calendar.get(Calendar.MILLISECOND)
+ calendar.get(Calendar.ZONE_OFFSET));
You might have to subtract the zone offset.
public class Time extends java.util.Date
It is not possible to cast Date to Time.
You can use this instead:
Time time = new Time(date.getTime())

How do I set a full date & time sql using java, and not just the date?

I am trying to set a timestamp in my database using java, however in my table all I get is the date, and no time (i.e., looks like "2010-09-09 00:00:00").
I am using a datetime field on my mysql database (because it appears that datetime is more common than timestamp). My code to set the date looks like this:
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Date timestamp = new java.sql.Date(today.getTime());
ps.setDate(1, timestamp);
ps.executeUpdate();
How do I set the date to include the time?
Edit: I changed the code as per below, and it sets both the date and the time.
PreparedStatement ps = conn.prepareStatement("INSERT INTO mytable (datetime_field) VALUES (?)")
java.util.Date today = new java.util.Date();
java.sql.Timestamp timestamp = new java.sql.Timestamp(today.getTime());
ps.setTimestamp(1, timestamp);
ps.executeUpdate();
Use java.sql.Timestamp and setTimestamp(int, Timestamp). java.sql.Date is date-only, regardless of the type of the column it's being stored in.
Not exactly sure what you need to use, but
ps.setDate();
expects a column type of Date. So it's normalizing it, removing the time.
Try
ps.setTimetamp();
You could use :
private static String getTimeStamp() {
SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return f.format(new Date());
}

Store date object in sqlite database

I'm using a database in my Java project and I want to store date in it, the 5th and the 6th parameter are Date Object. I used the solution below but I have errors in the indicated lines:
PreparedStatement creerFilm = connecteur.getConnexion().prepareStatement(
"INSERT INTO FILM (ID, REF, NOM, DISTRIBUTEUR, DATEDEBUT, DATEFIN) "+
"VALUES (?, ?, ?, ?, ?, ?)");
creerFilm.setInt(1, getId());
creerFilm.setString(2, getReference());
creerFilm.setString(3, getNomFilm());
creerFilm.setString(4, getDistributeur());
// These next two lines
creerFilm.setDate(5, new Date (getDateDebut().getDate()));
creerFilm.setDate(6, new Date (getDateFin().getDate()));
// The above two lines
creerFilm.executeUpdate();
creerFilm.close();
Can you help me to fix that please ?
Thank you
I can't really tell from your code, but you have to use java.sql.Date, not java.util.Date.
Here's how you convert from a utility date instance to an SQL date instance:
java.sql.Date date = new java.sql.Date(utilDate.getTime());
I think detailed answer you can read here: How to insert date in sqlite through java
In a short, you can insert Date as setString (or setInt, or setLong (see the above link), but not setDate):
PreparedStatement ps = connection.prepareStatement(<your sql>);
DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
ps.setString(1, df.format(<your date>));

Categories

Resources