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

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

Related

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

Update query for java JDBC +mysql database

I'm trying to run update query on table doctors. The primary key of the table is defined as a composite primary key (deptid, docid). What I'm trying to do is to update field designation, qualification and time based on deptid and docid (by another query).
I believe I'm doing something very silly but I'm not able to find it. Can someone help?
String did= request.getParameter("text1");
String dname = request.getParameter("text2");
String desig = request.getParameter("text3");
String qualification = request.getParameter("text4");
String time = request.getParameter("text5");
String className = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://192.168.10.13";
String user = "root";
String password = "";
PreparedStatement ps;
ResultSet rs;
try {
Class.forName(className);
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/webhospital","root","");
// PreparedStatement prepStmt = (PreparedStatement) conn.prepareStatement("Select * from tbl_userinfo");
ps = (com.mysql.jdbc.PreparedStatement) con.prepareStatement("update doctors set Designation=?,Qualification=?,Time= ? where deptid =? and docid IN(select docid from doctors where doctorname='dname';)");
ps.setString(1, did);
ps.setString(3,desig);
ps.setString(4,qualification);
ps.setString(5,time);
ps.executeUpdate();
} catch (ClassNotFoundException cx) {
out.println(cx);
} catch (SQLException ex) {
Logger.getLogger(MysqlInsertServlet.class.getName()).log(Level.SEVERE, null, ex);
}
ps = (com.mysql.jdbc.PreparedStatement) con.prepareStatement("update doctors set Designation=?,Qualification=?,Time= ? where deptid =? and docid IN(select docid from doctors where doctorname='dname';)");
ps.setString(1, did);
ps.setString(3,desig);
ps.setString(4,qualification);
ps.setString(5,time);
You have 4 question mark but set in wrong order why you don't set like :
ps.setString(1, desig);
ps.setString(2,qualification);
ps.setString(3,time);
ps.setString(4,deptId);
Supplying Values for PreparedStatement Parameters
You must supply values in place of the question mark placeholders (if
there are any) before you can execute a PreparedStatement object. Do
this by calling one of the setter methods defined in the
PreparedStatement class. The following statements supply the two
question mark placeholders in the PreparedStatement named updateSales:
updateSales.setInt(1, e.getValue().intValue());
updateSales.setString(2, e.getKey());
The first argument for each of these setter methods specifies the
question mark placeholder. In this example, setInt specifies the first
placeholder and setString specifies the second placeholder.
One change required in your query is
"where doctorname='dname';)" ==>> "where doctorname='"+dname+"';)"
I think without editing your code it is good to show you an simple example.
PrintWriter out = response.getWriter();
String Title = request.getParameter("Title");
String Artist = request.getParameter("Artist");
String Country = request.getParameter("Country");
String price = request.getParameter("price");
String Year = request.getParameter("Year");
try {
//loading driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//creating connection with the database
Connection con = DriverManager.getConnection("jdbc:derby://localhost:1527/sample", "app", "app");
PreparedStatement ps = con.prepareStatement("update COMPACT_DISK set TITLE=?,ARTIST=?,COUNTRY=?,PRICE=?,YEARS=? where TITLE=?");
ps.setString(1, Title);
ps.setString(2, Artist);
ps.setString(3, Country);
ps.setString(4, price);
ps.setString(5, Year);
ps.setString(6, Title);
int i = ps.executeUpdate();
if (i > 0) {
out.println("Compact disk successfully inserted");
}
} catch (Exception se) {
out.println("Error Occured : \n" + se.getLocalizedMessage());
se.printStackTrace();
}

How to use dynamic table name in SELECT query using JDBC

I have 5 or table table to query from \
my syntax i like this
String sql2 = "SELECT * FROM ? WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql2);
System.out.println("SQL before values are set "+sql2);
System.out.println("The values of table/test name recieved in TestPrint stage 1 "+tblName);
System.out.println("The values of test name recieved in TestPrint stage 1 "+key);
// values are outputted correctly but are not getting set in the query
pst.setString(1, tblName);
pst.setLong(2, key);
ResultSet rs2 = pst.executeQuery(sql2);
while(rs2.next()){
String ID = rs2.getString("ID");
jLabel35.setText(ID);
jLabel37.setText(ID);
jLabel38.setText(ID);
// them print command is initiated to print the panel
}
The problem is when i run this i get an error saying ".....you have and error in SQL syntax near ? WHERE Patient_ID = ?"
When i output the sql using system.out.println(sql2);
values are not set in sql2
When you prepare a statement, the database constructs an execution plan, which it cannot do if the table is not there. In other words, placehodlers can only be used for values, not for object names or reserved words. You'd have to rely on Java to construct your string in such a case:
String sql = "SELECT * FROM `" + tblName + "` WHERE Patient_ID = ?";
pst = conn.prepareStatement(sql);
pst.setLong(1, key);
ResultSet rs = pst.executeQuery();
String sqlStatment = "SELECT * FROM " + tableName + " WHERE Patient_ID = ?";
PreparedStatement preparedStatement = conn.prepareStatement(sqlStatment);
preparedStatement.setint(1, patientId);
ResultSet resultSet = preparedStatement.executeQuery();
public void getByIdEmployer() throws SQLException {
Connection con = null;
try {
con = jdbcUtil.connectionDtls();
PreparedStatement ptst = con.prepareStatement(getById);
ptst.setInt(1, 4);
ResultSet res = ptst.executeQuery();
while (res.next()) {
int empid = res.getInt(1);
System.out.println(empid);
String name = res.getString(2);
System.out.println(name);
int salary = res.getInt(3);
System.out.println(salary);
String location = res.getString(4);
System.out.println(location);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
con.close();
}
}

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

Date Java to MySql DateTime

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.

Categories

Resources