I have a method that calls an oracle procedure at the same time as it inserts into oracle, the insert statement works but the procedure does not. I am not receiving any errors. can anyone see why this isnt working?
Class.forName("oracle.jdbc.driver.OracleDriver");
String connectionString = "jdbc:oracle:thin:#" + oracle_ip_address + ":" + oracle_db_port + ":" + oracle_db_sid;
Connection conn = DriverManager.getConnection(connectionString, oracle_db_username, oracle_db_password);
ResultSet rs = stmt.executeQuery("Select * from Dropper");
CallableStatement cs = conn.prepareCall("{ call TTMS.job_vacationconflict_notify(?,?,?)}");
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy");
Statement stmt2 = conn.createStatement();
while (rs.next()){
String di = rs.getString("DROPPER_ID");
String sd = rs.getString("BEGIN_DT").replace(" 00:00:00.0", "");
String ed = rs.getString("END_DT").replace(" 00:00:00.0", "");
String vi = rs.getString("VACATION_ID");
String md = rs.getString("MODIFY_DT").replace(" 00:00:00.0", "");
query = "INSERT INTO DROPPER_VACATIONS(DROPPER_ID, BEGIN_DT, END_DT, CREATE_DT, CREATE_BY, MODIFY_DT, MODIFY_BY, COMMENTS, VACATION_ID) "
+ "VALUES ('"+di+"',to_date('"+sd+"','YYYY-MM-DD'),to_date('"+ed+"','YYYY-MM-DD'),sysdate,'MJRUTLED',to_date('"+md+"','YYYY-MM-DD'),'MJRUTLED','','"+vi+"')";
stmt2.executeUpdate(query);
cs.setInt(1,Integer.parseInt(di));
cs.setString(2,sdf.parse(sd).toString());
cs.setString(3,sdf.parse(ed).toString());
cs.execute();
}
Does your procedure expect dates as input? If it does, try to pass date values and not rely on implicit conversion. If the SP expects strings, make sure you format the dates exactly the same way that the SP expects (add debug print on both sides, dbms_output and dbms_pipe are your friends).
Also, please consider using parameter substitution for query; this code begs for SQL injection %)
Related
I'm currently writing a java application which is used to print bar codes out, which the information for is obtained from a MySQL database. The data in SQL has a property which defines which type of bar code it is, value 1 = serialized and 2 = un-serialized. I was wondering how I would use an if statement to set a variable to define what type of bar-code is being used - in java.
On the SQL database the value for bar code type is 'FK_BarcodeTypeID'
The code I have so far is:
String SQL ="SELECT [PK_PrintQueueID]" +
" ,[FK_PrinterID]" +
" ,[FK_BarcodeTypeID]" +
" ,[Barcode]" +
" ,[Quantity]" +
" ,[QueueDate]" +
" ,[ProcessedDate]" +
" FROM [Brad].[dbo].[PrintQueue]" +
" WHERE ProcessedDate IS NULL";
//Declare variable connection.
Connection connection = null;
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//get current date time with Date()
Date date = new Date();
// System.out.println(dateFormat.format(date));
//
try {
connection = DriverManager.getConnection(connectionString);
Statement stmt = connection.createStatement();
Statement stmt2 = null;
ResultSet rs = stmt.executeQuery(SQL);
while (rs.next()) {
System.out.println(rs.getString("Barcode"));
// System.out.println(rs.getString("PK_PrintQueueID"));
// System.out.println(rs.getString("ProcessedDate"));
String SQL2 = "UPDATE PrintQueue SET ProcessedDate = '"+dateFormat.format(date)+"' WHERE PK_PrintQueueID = '"+rs.getString("PK_PrintQueueID")+"' ";
// System.out.println(SQL2);
String ZPL = "^XA ^FX BARCODE ^BY4,2,050 ^FO140,40^BC^FD"+rs.getString("Barcode")+"^FS ^XZ";
System.out.println(ZPL);
// THIS IF STATEMENT SETS TYPE OF BARCODE TO
// TYPE 1 OR 2
I tried using the following but had no luck;
String BCSerialized = "SELECT * FROM PrintQueue WHERE FK_BarcodeTypeID = '1'";
System.out.println(BCSerialized);
String BCUnSerialized = "SELECT * FROM PrintQueue WHERE FK_BarcodeTypeID = '2'";
System.out.println(BCUnSerialized);
I am struggling to work out how to do the above, therefore any advice is appriciated.
Thankyou!
I have to check the rooms available during a particular period ie from a starting date to an ending one for a hotel reservation system. To choose a starting and ending date, I used a JCalendar. The problem is that I am getting an error when I am creating the SQL string query and also I don't know how to retrieve the date from the JCalendar to be used in the query.
Below are code snippets of what I have done and where I am stucked.
JCalendar instantiation:
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
Query to check for rooms available:
ResultSet rs = null;
Connection conn = null;
Statement stmt = null;
try {
// new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/testing?autoReconnect=true&useSSL=false";
String connectionUser = "root";
String connectionPassword = "admin";
conn = DriverManager.getConnection(connectionUrl, connectionUser,
connectionPassword);
stmt = conn.createStatement();
String query = "select * from testing.room as ro
where ro.room_id not in
(
select re.room_no
from testing.booking as re
where (arrival_date >= "2016-05-24" and departure_date < "2016-05-29")
or (departure_date >= "2016-05-24" and arrival_date < "2016-05-29")
)";
rs = (ResultSet) stmt.executeQuery("");
while (rs.next()) {
System.out.println(rs.getString(1) + " " + rs.getString(2)
+ " " + rs.getString(3)+ " " + rs.getString(4)+ " "+ rs.getString(5));
}
} catch (Exception e) {
e.printStackTrace();
}
I have hardcoded the dates here :
where (arrival_date >= "2016-05-24" and departure_date < "2016-05-29")
or (departure_date >= "2016-05-24" and arrival_date < "2016-05-29")
That's because I don't know how to take the values from the JCalendar to write it there ie should I use PreparedStatements and get the text or something?
And also, I am getting an error with the query ie where I wrote String query= "query" as it says "Insert missing quotes".
You need to make two changes here:
Get the dates from JDateChooser fields (by calling getDate() method on JDateChooser objects).
Use PreparedStatement and set the dates dynamically. Below is an exmple:
JDateChooser arrival = new JDateChooser();
JDateChooser departure = new JDateChooser();
PreparedStatement pStmt = conn.prepareStatement("select * from testing.room where arrival_date >= ? and departure_date < ?");
pStmt.setDate(1, arrival.getDate());
pStmt.setDate(2, departure.getDate());
ResultSet rs = preparedStatement.executeQuery();
I am trying to write a query and get results from oracle db using java and jdbc. My problem is the same query works if I try with statement, but the same query does not work if I use preparedStatement.
Statement Code: (Here I get real count value)
Statement stmt = con.createStatement();
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
rs = stmt.executeQuery(sql);
PreparedStatement Code: (Here I get count value zero)
Date sqlDate = new java.sql.Date(someJava.Util.Date.getTime());// = 2015-09-24
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE(?,'YYYY-MM-DD')";
pstmt = con.prepareStatement(sqlString);
pstmt.setDate(1, sqlDate);
rs = pstmt.executeQuery();
When I sysout my sqlDate prints like: 2015-09-24.
I have same problem with some other queries.
Can anyone know whats wrong here?
The TO_DATE function converts a string to a date given a certain format. So the parameter passed to the prepared statement should be the String to be converted by the Oracle function:
pstmt.setString(1, sqlDate.toString());
Or you can change the query so that the parameter is the date itself and pass the java.sql.Date object to the prepared statement:
sqlString = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = ?";
pstmt.setDate(1, sqlDate());
Note that, for the normal statement query:
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate + "','YYYY-MM-DD')";
the String concatenation will append the string representation of the object, i.e. it is equivalent to:
String sql = "SELECT COUNT(*) CNT FROM DB.TABLE WHERE DAY = TO_DATE('" + sqlDate.toString() + "','YYYY-MM-DD')";
I am trying to use the setString(index, parameter) method for Prepared Statements in order to create a ResultSet but it doesn't seem to be inserting properly. I know the query is correct because I use the same one (minus the need for the setString) in a later else. Here is the code I currently have:
**From what I understand, the ps.setString(1, "'%" + committeeCode + "%'"); is supposed to replace the ? in the query but my output says otherwise. Any help is appreciated.
public String getUpcomingEvents(String committeeCode) throws SQLException{
Context ctx = null;
DataSource ds = null;
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
StringBuilder htmlBuilder = new StringBuilder();
String html = "";
try {
ctx = new InitialContext();
ds = (DataSource) ctx.lookup("java:ConnectDaily");
conn = ds.getConnection();
if(committeeCode != null){
//get all events
String queryStatement = "SELECT " +
.......
"WHERE c.calendar_id = ci.calendar_id AND c.short_name LIKE ? " +
"AND ci.style_id = 0 " +
"AND ci.starting_date > to_char(sysdate-1, 'J') " +
"AND ci.item_type_id = cit.item_type_id " +
"ORDER BY to_date(to_char(ci.starting_date), 'J')";
ps = conn.prepareStatement(queryStatement);
ps.setString(1, "'%" + committeeCode + "%'");
System.out.println(queryStatement);
rs = ps.executeQuery();
if (rs != null){
while(rs.next()){
String com = rs.getString("name");
String comID = rs.getString("short_name");
String startTime = rs.getString("starting_time");
String endTime = rs.getString("ending_time");
String name = rs.getString("contact_name");
String desc = rs.getString("description");
String info = rs.getString("contact_info");
String date = rs.getString("directory");
htmlBuilder.append("<li><a href='?com="+committeeCode+"&directory=2014-09-10'>"+com+" - "+ date +" - "+startTime+" - "+endTime+"</a> <!-- Link/title/date/start-end time --><br>");
htmlBuilder.append("<strong>Location: </strong>"+comID+"<br>");
htmlBuilder.append("<strong>Dial-In:</strong>"+com+"<br>");
htmlBuilder.append("<strong>Part. Code:</strong>"+info+"<br>");
htmlBuilder.append("<a href='http://nyiso.webex.com'>Take me to WebEx</a>");
htmlBuilder.append("</li>");
}
}
html = htmlBuilder.toString();
.
.
.
}catch (NamingException e) {
e.printStackTrace();
//log error and send error email
} catch (SQLException e) {
e.printStackTrace();
//log error and send error email
}finally{
//close all resources here
ps.close();
rs.close();
conn.close();
}
return html;
}
}
Output
14:18:22,979 INFO [STDOUT] SELECT to_char(to_date(to_char(ci.starting_date), 'J'),'mm/dd/yyyy') as start_date, to_char(to_date(to_char(ci.ending_date), 'J'),'mm/dd/yyyy') as end_date, to_char(to_date(to_char(ci.starting_date), 'J'),'yyyy-mm-dd') as directory, ci.starting_time, ci.ending_time, ci.description, cit.description as location, c.name, c.short_name, ci.add_info_url, ci.contact_name, ci.contact_info FROM calitem ci, calendar c, calitemtypes cit WHERE c.calendar_id = ci.calendar_id AND c.short_name LIKE ? AND ci.style_id = 0 AND ci.starting_date > to_char(sysdate-1, 'J') AND ci.item_type_id = cit.item_type_id ORDER BY to_date(to_char(ci.starting_date), 'J')
There is no need for the quotes in setString:
ps.setString(1, "%" + committeeCode + "%");
This method will bind the specified String to the first parameter. It will not change the original query String saved in queryStatement.
The placeholder remains as part of the SQL text.
The bind value is passed when the statement is executed; the actual SQL text is not modified. (This is one of the big advantages of prepared statements: the same exact SQL text is reused, and we avoid the overhead of a hard parse.
Also note that you are including single quotes within the value, which is a bit odd.
If the bind placeholder were to be replaced in the SQL text, assuming committeeCode contains foo, the equivalent SQL text would be:
AND c.short_name LIKE '''%foo%'''
which will match only c.short_name values that begin and end with a single quote, and contain the string foo.
(This looks more like Oracle SQL syntax than it does MySQL.)
As we know that in setString we can pass string value only, So even if we write the code like this:
String param="'%"+committeeCode+"%'";
And if you print the value of param it will throw error, Hence you cannot use it as well in prepared statement.
You need to modify modify it little bit as:
String param="%"+committeeCode+"%";(Simpler one, other way can be used)
ps.setString(1,param);
This exception is occur in mentioned section of my code:
Connection con = null;
PreparedStatement ps = null;
ResultSet rs = null;
String query = "Insert into ...";
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query, java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate(query);
rs = ps.getGeneratedKeys(); // Exception is here
}
while (resultset.next()) {
id = String.valueOf(resultset.getInt(1));
}
Exception:
Generated keys not requested. You need to specify Statement.RETURN_GENERATED_KEYS to Statement.executeUpdate() or Connection.prepareStatement()
My purpose is inserting a new record and save the first field (id) (that is auto_increment) to variable id.
You are using the wrong execute method. Instead of the one taking a String, you should use one without a parameter. And as Chris Joslin mentioned, for INSERT it is better to use executeUpdate.
Technically a correct JDBC driver should throw an SQLException immediately when calling execute(String) or one of its siblings on a PreparedStatement, but some drivers ignore this rule.
Try ps.executeUpdate() instead of ps.execute().
Shouldn't it be:
String query = "Insert into Books(Name,ISBN,Status,Date)" +
"values( '" + name + "','" + isbn + "','" + status+ "','" + date + "' ) ";
try {
con = DriverManager.getConnection(...);
ps = con.prepareStatement(query,java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate();
rs = ps.getGeneratedKeys(); // Exception is here
}
It looks like in your first example, you do a prepare correctly, but then call the executeUpdate with the Query String again instead of just the ps.executeUpdate().
ps = con.prepareStatement(query, java.sql.Statement.RETURN_GENERATED_KEYS);
ps.executeUpdate(query);