Date Java to MySql DateTime - java

every body. I am getting this error:
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 '14:37:41)' at line 1
for this piece of code
public String addName() {
// TODO Auto-generated method stub
try {
java.util.Date dt = new java.util.Date();
java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat(
"yyyy-MM-dd HH:mm:ss");
String currentTime = sdf.format(dt);
String name = "RandomName";
Connection connect = DriverManager.getConnection(
"jdbc:mysql://localhost", "ericman", "ericman");
Statement stat = (Statement) connect.createStatement();
String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES ('"
+ name + "', " + currentTime + ")";
stat.executeUpdate(insert);
} catch (Exception e) {
System.out.println(e);
}
return "Name Updated";
}
Any suggestion of why this happening, I suck on structured language just so you know :)

Use PreparedStatement.
String insert = "INSERT INTO `bookcatalog`.`puch` (`name`, `time`) VALUES (?,?)";
PreparedStatement ps=connect.prepareStatement(insert);
ps.setString(1,name);
ps.setTimeStamp(2,TimeStamp.valueOf(currentTime));
ps.executeUpdate();

You are missing ' characters around your currentTime in the insert statement.
However, you really should be using a prepared statement for such things, to guard against SQL injection attacks.

Try convert string to date by str_to_date

Do you need to encapsulate the date/time in your INSERT statement with inverted commas, like you do with the name argument?

ugh. Why don't you use a PreparedStatement instead?
PreparedStatement stmt = connect.prepareStatement("INSERT INTO bookcatalog.puch(name, time) values ?,?");
stmt.setString(1, name);
stmt.setTimestamp(2, dt);
stmt.execute();
It's far cleaner.

Related

SQL Error or missing database syntax error

I get an sql error when trying to insert something into my DB.
I give a bunch of input to my method, convert that input into strings or sql time and want to store it.
public static void setCourseList(String courseDescription, String courseName, LocalTime courseStart, LocalTime courseEnd, LocalDate courseDate, DayOfWeek courseDay) {
Connection conn = null;
try {
// db parameters
// path to db relative to run time directory
String url = "jdbc:sqlite:Holiday.db";
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
conn = DriverManager.getConnection(url);
System.out.println("Connected");
Statement stmt = conn.createStatement();
PreparedStatement pstmt = conn.prepareStatement(sqlInsertCourse);
pstmt.setString(1, courseName);
String courseStartString = courseStart.toString();
pstmt.setString(2, courseStartString);
java.sql.Time courseEndTime = Time.valueOf(courseEnd);
pstmt.setTime(3, courseEndTime);
java.sql.Date courseDateDate = java.sql.Date.valueOf(courseDate);
pstmt.setDate(4, courseDateDate);
String courseDayString = courseDay.toString();
pstmt.setString(5, courseDayString);
pstmt.executeUpdate();
pstmt.close();
System.out.println("Connection to SQLite has been established.");
// create tables if they do not exists
stmt.execute(sqlInsertCourse);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
try {
if (conn != null) {
conn.close();
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
}
}
I would expect it to store the input in my db.
I do get an [SQLITE_ERROR] SQL error or missing database (near ")": syntax error) error instead.
Any help is appreciated.
I am new to sql.
Change
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?,);";
To
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (?, ?,?, ?,?, ?);"; //<<<<<<<<<< extra comma removed
As per the comment on the line the final comma after the last ? has been removed.
Same as what Mike has answered, you can change it to
String sqlInsertCourse = "INSERT INTO COURSE (Name,Start,End,Date,Day,Description) VALUES (""put values here"");";
If you are wondering why it doesn't throw you an error, it's because there is no syntax error in the java, there's an error in the SQL which only the database can throw, but you're computer can't recognize. Hope this answers your question.

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();

"incompatible datatypes in combination" error with query on date value

The intent of my overall program is to fetch values from Access database and display in jtable for a particular date.
I have a table in access database where for_date field is stored as a Date/Time field and format is Short date(dd-MM-yyyy). Now my program requires me to retrieve the rows from the database for a particular date.I used SimpleDateFormat to convert it in the format as access database but it gives error. The error I get is:- net.ucanaccess.jdbc.UcanaccessSQLException:UCAExc:::3.0.4 incompatible datatypes in combination.This exception may happen if you add integers representing units of time directly to datetime values using the arithmetic plus operator but without specifying the unit of date.In this specific case you have to use,for example, +1 DAY
My code is as follows:-
String table_sel = "ISGS_table";
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String date1 = sdf.format(report_date.getDate());
try{
String sql = "Select reporting_date as REPORTING_DATE,for_date as FOR_DATE,outage_date as OUTAGE_DATE,outage_time as OUTAGE_TIME,stat_detail as STATION_DETAILS,res_date as RESTORATION_DATE,rest_time as RESTORATION_TIME,rest_reason as RESTORATION_REASON from " + table_sel+" where for_date='" + date1 + "'";
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();
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
You are receiving that error message because you are passing the value for for_date as a string literal. UCanAccess follows the Access SQL convention of using hash marks (#) as the delimiter for date/time literals.
So, this will fail with the error you cited
... WHERE for_date = '2017-02-03'
whereas this will work
... WHERE for_date = #2017-02-03#
Note that it would be considered better form if you were to use a PreparedStatement with
... WHERE for_date = ?
and pass the date value using PreparedStatement#setDate.

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();

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

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);
}

Categories

Resources