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();
Related
I am new to using java with a database and I have been trying following code:
public int getDateDiff(int OrderID) {
Connection conn = DBConnection.getConnection();
Integer diff = null;
String getdiffSQL = "SELECT DATEDIFF( DAY , StartDate , EndDate ) FROM CarOrder WHERE OrderID = ?;";
try {
PreparedStatement pstm = conn.prepareStatement(getdiffSQL);
pstm.setInt(1, OrderID);
ResultSet rs = pstm.executeQuery(getdiffSQL);
while (rs.next()) {
diff = rs.getInt(1);
}
}
catch (SQLException ex) {
System.out.println("Error: " + ex.getMessage());
}
return diff;
}
I tried running this but i encounter this
"Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException"
and the the return diff is null. Please tell me what wrong in this and how do i fix this.
PreparedStatement#executeQuery() does not take a parameter and you should not be passing the query string. Instead use this pattern:
PreparedStatement pstm = conn.prepareStatement(getdiffSQL);
pstm.setInt(1, OrderID);
ResultSet rs = pstm.executeQuery(); // no parameter
This is a fairly common mistake made when using JDBC, partly because Statement#executeQuery() does take the query string as a parameter. Add to this tutorials like MkYong which make the same mistake as the OP and it is easy to see why this error is so prevalant.
I have the following line of code that I am trying to execute:
List<File> sectList = new ArrayList<File>();
try {
String query = "SELECT * FROM legaf WHERE ida = ?";
PreparedStatement preparedStmt = connection.prepareStatement(query);
preparedStmt.setInt(1, idforfile);
ResultSet result = preparedStmt.executeQuery(query);
while (result.next())
{
fls.add(result.getInt("idf"));
}
}
catch (SQLException ex)
{
ex.printStackTrace();
}
but I receive the following exception:
java.sql.SQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '?' at line 1
which points at the following statement:
ResultSet result = preparedStmt.executeQuery(query);
I am trying to apply the query to a XAMPP MySQL database. I am using Intellij.
fls is declared as
private List<Integer> fls = new ArrayList<Integer>();
Write
preparedStmt.executeQuery();
and not
preparedStmt.executeQuery(query);
else you are executing Statement.executeQuery(String) which does not resolve parameters in the query string.
You don't need to pass in the query string to executeQuery().
Change this:
ResultSet result = preparedStmt.executeQuery(query);
to this:
ResultSet result = preparedStmt.executeQuery();
Primary offenders among tutorials promoting passing in the query string is MkYong:
https://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/
Here we find the following line:
ResultSet rs = preparedStatement.executeQuery(selectSQL );
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.
I want to link the mysql database using Java, execute query returns the record of the specified period, and finally present the result in form of table in java.
How can I convert the input string into the mysql valid date and output the result?
I tried this, but failed.
Connection con = DBCon.dbcon();
java.util.Date t1= new SimpleDateFormat("yyyyMMdd").parse(jTextField2.getText());
java.util.Date t2= new SimpleDateFormat("yyyyMMdd").parse(jTextField3.getText());
PreparedStatement query = con.prepareStatement(SELECT * FROM transaction WHERE TransactionDate >= ? and TransactionDate <= '"+t1+"' and id1=?);
ResultSet rs = query.executeQuery();
Thank you very much!!!
You have to set parameters to PreparedStatement instance as follows:
Connection con = DBCon.dbcon();
java.util.Date t1= new SimpleDateFormat("yyyyMMdd").parse(jTextField2.getText());
java.util.Date t2= new SimpleDateFormat("yyyyMMdd").parse(jTextField3.getText());
PreparedStatement query = con.prepareStatement(SELECT * FROM transaction WHERE TransactionDate >= ? AND TransactionDate <= ? AND id1 = ?);
query.setDate(1,new java.sql.Date(t1.getTime()));
query.setDate(2,new java.sql.Date(t2.getTime()));
query.setLong(3,id);// Assuming Datatype of Id to Long and value in variable id, Change accordingly if not.
ResultSet rs = query.executeQuery();
Edit : Changed datatype of setDate from java.util.Date to java.sql.Date
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.