cannot insert java.sql.Date to the "Date" field in the database - java

I am getting a string value such as "2012-01-20" and converting it to sql.Date to insert it in the database.
code
java.util.Date DOB = new java.util.Date();
String datetext = txtDate.getText();
SimpleDateFormat sd = new SimpleDateFormat("yyyy-mm-dd");
DOB = sd.parse(datetext);
java.sql.Date sqlDate = new java.sql.Date(DOB.getTime());
String query = "ISERT INTO EMPLOYEE ('DOB')"
+ " VALUES ( ? ) ";
con = db.createConnection();
try{
ps = con.prepareStatement(query);
ps.setDate(1, sqlDate);
ps.executeQuery();
}catch(Exception ex){
System.err.print(ex);
}
When i run this code I am getting an exception ""[Microsoft][ODBC SQL Server Driver]Optional feature not implemented"
what am i doing wrong here ? pls help !

Remove single quote - ('DOB') and INSERT (misspell)
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
You may use java.sql.Date.valueOf("2012-01-20") method to convert string to sql date.
Use executeUpdate() method instead of executeQuery().
String query = "INSERT INTO EMPLOYEE (DOB) VALUES (?)";
con = db.createConnection();
try{
ps = con.prepareStatement(query);
ps.setDate(1, java.sql.Date.valueOf("2012-01-20"));
//Or use
// ps.setTimestamp(1, new Timestamp(DOB.getTime()));
ps.executeUpdate();
}catch(Exception ex){
System.err.print(ex);
}

Related

Exception: UCAExc:::4.0.2 unexpected token: 2017 required: )

When I insert date to microsoft Access it gives me this error, why?
what it means? I am sure that the query is correct.
this is my code:
try {
final DateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss a");
Date date = new Date();
String a = "#"+sdf.format(date)+"#";
conn=DriverManager.getConnection(dbURL);
System.out.println("Connection ok.");
id = Integer.parseInt(ID.getText());
String query = "INSERT INTO Patient(ID, FName, Address, Phone, Allergies)\n" +
"VALUES ('"+id+"', '"+ name.getText()+"', '"+ address.getText()+"', '"+phone.getText()+"', '"+allergies.getText()+ "');";
PreparedStatement stmt = conn.prepareStatement(query);
stmt.executeUpdate();
String query2 = "INSERT INTO Visit( PatientID, ArrivalTime, HeartRate, Temprature) "+
"VALUES ('"+id+"','"+a+"', '"+heart.getText()+"', '"+temp.getText()+"');";
stmt = conn.prepareStatement(query2);
stmt.executeUpdate();
conn.close();
}catch(Exception e){
System.err.println("Exception: "+e.getMessage());
}
With the statement
String a = "#"+sdf.format(date)+"#";
you have already put # delimiters around the date string. Then your dynamic SQL proceeds to put ' delimiters around that, resulting in something like
INSERT INTO Visit (PatientID, ArrivalTime, ...) VALUES ('1', '#12/29/2017 06:24:23 PM#', ...);
which is invalid syntax. The correct literal syntax would be ...
INSERT INTO Visit (PatientID, ArrivalTime, ...) VALUES (1, #12/29/2017 06:24:23 PM#, ...);
... but you really should not be using dynamic SQL. You should be using a parameterized query along the lines of
// test data
int id = 123;
java.util.Date date = new java.util.Date();
String sql = "INSERT INTO Visit (PatientID, ArrivalTime) VALUES (?,?);";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.setTimestamp(2, new java.sql.Timestamp(date.getTime()));
ps.executeUpdate();

How to filter data by date (obtained from a JCalendar) using MySQL

I'm having a hard time trying to filter data by date
MySQL Query
public DefaultTableModel getData1(Date start,Date end){
.......
String sql = "SELECT * FROM torch.new_table WHERE pro_date between '"+start+"' and '"+end+"'";
.....
}
Code for get date from a JCalendar
DefaultTableModel dm = new Products().getData1(sDate.getDate(), eDate.getDate());
Complete code is Here: http://postimg.org/image/4zycbtj4n/
Use the wildcard '?' when you are defining the query.
Replace each wildcard using setDate and a new java.sql.Date.
...
String sql = "SELECT * FROM torch.new_table WHERE pro_date between ? and ?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, new java.sql.Date(start.getTime());
ps.setDate(2, new java.sql.Date(end.getTime());
ResultSet rs = ps.executeQuery();
...
If you obtain a String from a JDateChooser, you can use
ps.setDate(1, java.sql.Date.valueOf(start));
ps.setDate(2, java.sql.Date.valueOf(end));
More possibilities here Using setDate in PreparedStatement
Part of code to filter data by date (Obtained from a jCalender) using MySQL
Thanks for help #RubioRic
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//dateT and dateE type jDatechooser
String get = sdf.format(dateT.getDate());
String get1 = sdf.format(dateE.getDate());
// Query to select get data from database
String sql = "SELECT * FROM date WHERE DATE(Date) >= ? && DATE(Date) <= ?";
try{
Connection conn = dataB.mySqlCon();
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, get);
st.setString(2, get1);
ResultSet rs = st.executeQuery();

Using Timestamp in java sql prepared statement

I am trying to execute a select query using prepared statement in Java.
In Where clause im checking for a condition on Timestamp type column as shown below.
String selectSQL = "select * from db.keycontacts WHERE CREATEDDATETIME>?";
PreparedStatement preparedStatement = connect.prepareStatement(selectSQL);
preparedStatement.setTimestamp(1, convertStrToTimestamp(lastSyncTimeStamp));
resultSet = preparedStatement.executeQuery(selectSQL );
//function to convert timestampString to java.sql.Timestamp
private java.sql.Timestamp convertStrToTimestamp(String dateTimeStr){
java.sql.Timestamp timeStampDate = null;
try {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");//2015-05-11 18:26:55
java.util.Date dateObj = (java.util.Date)formatter.parse(dateTimeStr);
timeStampDate = new Timestamp(dateObj.getTime());
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return timeStampDate;
}
When the query is executed, getting following exception.
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '?' at line 1
So where exactly im going wrong here?
thanks in advance.
Remove the parameter from
resultSet = preparedStatement.executeQuery(selectSQL );
and change to
resultSet = preparedStatement.executeQuery( );
The query you passed in preparedStatement.executeQuery(selectSQL ); takes priority over the query you passed in connect.prepareStatement(selectSQL); which is the simple string ("select * from db.keycontacts WHERE CREATEDDATETIME>?") in which you dint set any parameter so there is a syntax error for ?
and you can also say that statement is prepared at PreparedStatement preparedStatement = connect.prepareStatement(selectSQL); since executeQuery() is inherited from Statement it will execute query without preparing it.
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/test","root","rootpasswd");
PreparedStatement ps = con.prepareStatement("select p.PARKING_NUMBER, p.TYPE, p.AVAILABLE, "
+ "t.PARKING_NUMBER, t.VEHICLE_REG_NUMBER, t.PRICE, t.IN_TIME, t.OUT_TIME "
+ "from parking p inner join ticket t on p.PARKING_NUMBER = t.PARKING_NUMBER "
+ "where t.In_TIME = ?");
Timestamp ts = new Timestamp(BigDecimal.valueOf(expectedInTime.getTime()/1000d).setScale(0, RoundingMode.HALF_UP).longValue()*1000);
//To Round Half Up from millisecond (d for double) to second (long so no d) because MySQL do this.
ps.setTimestamp(1, ts);
ResultSet rs = ps.executeQuery();

Whats the sql query for retrieving data from database between two dates, if the date values are stored on a variable?

I have been using MS access database, and i used this code to fetch records from the database on which it was working perfect. But now, as i changed my database to mysql, this piece of code is not fetching records from database. The database connections are working. The dates entered in the textbox are stored to a variable and i want to use that variables to fetch records from the database. Thanks for the help in advance.
java.util.Date StartDate=(java.util.Date)textField1.getValue();
java.util.Date EndDate=(java.util.Date)textField2.getValue();
java.sql.Date startDate = new java.sql.Date(StartDate.getTime());
java.sql.Date endDate = new java.sql.Date(EndDate.getTime());
PreparedStatement ps = conn.prepareStatement("select * from table_nm where 'Date1 BETWEEN #startDate# AND #endDate#' ");
ResultSet rs = ps.executeQuery();
while(i8rs.next())
{
Date i8Date = rs.getDate("Date1");
String i8ItemName = rs.getString("Item_Name");
int i8Quantity = rs.getInt("Quantity");
Double i8Rate = rs.getDouble("Rate");
Double i8total = rs.getDouble("Total");
Object[] row = new Object[5];
row[0] = i8Date;
row[1] = i8ItemName;
row[2] = i8Quantity;
row[3] = i8Rate;
row[4] = i8total;
tableModel.addRow(row);
}
Assuming that Date1 is the column name in your table.
Change:
PreparedStatement ps =
conn.prepareStatement("select * from table_nm
where 'Date1 BETWEEN #startDate# AND #endDate#' ");
To:
PreparedStatement ps =
conn.prepareStatement("select * from table_nm
where Date1 BETWEEN ? AND ? ");
ps.setDate( 1, startDate );
ps.setDate( 2, endDate );
Refer To:
Java: Using Prepared Statements
Just use this
PreparedStatement ps = conn.prepareStatement("select * from table_nm
where Date1 BETWEEN ? AND ? ");
ps.setDate( 1, startDate );
ps.setDate( 2, endDate );
ResultSet rs = ps.executeQuery();
while(rs.next())
{
// your table values

PreparedStatement sql setDate

I have this query :
String sql ="select col1,col2,col3 from table where tstamp between '01/01/2014 00:00' and '01/01/2014 23:59'" ;
I want to use a PreparedStatement to setDate like this :
String sql = "select col1,col2,col3 from table where tstamp between ? and ? " ;
PreparedStatement p = connection.prepareStatement(sql);
p.setDate(1,..);
and I don't know how to do it..please help
I tried the new Date(int,int,int) constructor but it doesn't set the hours and minutes.
JDBC has three temporal types, all in the java.sql package:
Date, which contains a date without time
Time, which contains a time without date
Timestamp, which contains a date and a time.
You thus need to use a Timestamp, and the setTimestamp() method of PreparedStatement.
To construct a Timestamp instance from a String, use a SimpleDateFormat to parse the String into a java.util.Date object, then construct the Timestamp by passing the milliseconds obtained from this java.util.Date object.
Use java.sql.Date
try{
sql = "select col1,col2,col3 from table where tstamp between ? and ? ;
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, /**Your Date**/);
pstmt.setString(2, /**Your Date**/);
rs = pstmt.executeQuery();
.
.
.
}catch (Exception e) {
e.printStackTrace();
}finally{
sql = null;
if(rs != null){
rs.close();
rs = null;
}
if(pstmt != null){
pstmt.close();
pstmt = null;
}
if(conn != null){
conn.close();
conn = null;
}
}
For More
The problem is that the Date object from java.sql is different that the Date from java.util
Then if You use p.setDate(1,..); with a java.util.Date You will lose the time.
One possible solution could be that You passed as argument a Date from java.sql

Categories

Resources