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!
Related
I am trying to call two sets of data from two different tables to display in a JTextArea (jtaDisplay). The first table (emp_db) will get the employee number, name and surname. The second table (sec_clearance) will get the employee security clearance level.
The method is placed in the constructor so it will execute when the frame starts up, but whenever I run the frame it does not display the data. No error messages come up and the stack trace doesn't display any error messages.
I placed a JOptionPane in various places inside the method to see where the problem lies exactly and found that the while(rs.next()) statement is not executing as the JOptionPane displays outside the while statement but not inside it.
Here is the code I currently have:
try
{
String user = txtEmpTitle.getText();
String encuser = encrypt(user); //encrypting employee number with AES to read in database
String getEmpNum = "Select * from emp_db where emp_num = '" + encuser + "'";
String getSecLevel = "select secLevel from sec_clearance where emp_num = '" + encuser + "'";
Class.forName("com.mysql.jdbc.Driver");
Connection conn = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:3306/employee_database","root","pass123");
Statement stmt=conn.createStatement();
Statement stmt2=conn.createStatement();
ResultSet rs = stmt.executeQuery(getEmpNum);
ResultSet rs2 = stmt2.executeQuery(getSecLevel);
while(rs.next() && rs2.next())
{
String empNum = rs.getString("emp_num");
String empName = rs.getString("fname");
String empSname = rs.getString("sname");
String empSecLevel = rs2.getString("secLevel");
//decrypting data in database
String decNum = EmpEditDB.decrypt(empNum);
String decName = EmpEditDB.decrypt(empName);
String decSname = EmpEditDB.decrypt(empSname);
String decSecLevel = EmpEditDB.decrypt(empSecLevel);
jtaDisplay.setText("Employee number: " + decNum +
"\nEmployee name: " + decName + " " + decSname +
"\nSecurity clearance: " + decSecLevel);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this, e);
}
How can I get the code in the while statement to execute and display data in the JTextArea?
only if you have record ,it will come into while loop.Better use preparedstatement for dynamic value setting.For debugging purpose try to print your query in debugging and copy the query and execute in sql tool for checking whether any records.
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 working on account management system. Goal is to set trial period into db. I am getting Timestamp "2015-10-30 22:55:48" from jsonObject into REST service and inserting into db using prepared statements. But each time I am getting effected rows 0 and means update operation is not performed!
I have tried following piece of code including parsing and conversion:
JSONParser parser = new JSONParser();
Object obj = parser.parse(requestBody);
JSONObject jsonObject = (JSONObject) obj;
String accountExpiryStr = jsonObject.get("accountExpiry").toString();
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date parsedDate = dateFormat.parse(accountExpiryStr);
Timestamp accountExpiry = new Timestamp(parsedDate.getTime()); // accountExpiry output is 2015-10-30 22:55:48.0
String requestQuery = "UPDATE table SET Account_Expiry = ?"
+ "WHERE Account_Id = ? "
+ "AND User_Id = ? ";
preparedStatement = con.prepareStatement(requestQuery);
preparedStatement.setTimestamp(1, accountExpiry);
preparedStatement.setInt(2, Integer.parseInt((String) jsonObject.get("selectedUserId")));
preparedStatement.setInt(3, Integer.parseInt((String) jsonObject.get("accountId")));
rowCount = preparedStatement.executeUpdate();
System.out.println("Effected Rows: " + rowCount);
Affected rows = 0 means that the where clause of the UPDATE did not match any record in your table. So you should first check if the where clause is correct.
Seems you have switched user id and account id...
Instead write:
preparedStatement.setInt(2, Integer.parseInt((String) jsonObject.get("accountId")));
preparedStatement.setInt(3, Integer.parseInt((String) jsonObject.get("selectedUserId")));
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);
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 %)