Eliminate the exception - java

Hi i have the following code which deletes a row in a sql table. The user clicks on an item in a jlist. The item in the jlist is deleted.
public class listdisplay implements ActionListener, ListSelectionListener {
#Override
public void valueChanged(ListSelectionEvent a) {
Object obj = lstcourses.getSelectedValue() ;
String obj1 = obj.toString() ;
// System.out.println(obj1) ;
String sql= " SELECT *" +
" FROM courseofferinguom " +
" WHERE professorid=" +
" '"+teacher.getTeacherIDint()+"'" +
" AND coursenumber = (SELECT coursenumber "+"FROM courseuom WHERE coursename = '"+obj1+"') " ;
try {
statement = con.prepareStatement(sql);
ResultSet rs = statement.executeQuery();
if (rs != null) {
while(rs.next())
{
txtcnum.setText(rs.getString(1)) ;
txtdaysoftheweek.setText(rs.getString(4)) ;
txttime.setText(rs.getString(5)) ;
txtlocation.setText(rs.getString(6)) ;
txtcredithours.setText(rs.getString(7)) ;
String open = "Open" ;
if ( rs.getString(8).equals(open)) {
chkopen.setSelected(true);
}
}
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
#Override
public void actionPerformed(ActionEvent e) {
Object obj = lstcourses.getSelectedValue() ;
String obj1 = obj.toString() ;
String sql= " DELETE " +
" FROM courseofferinguom " +
" WHERE professorid=" +
" '"+teacher.getTeacherIDint()+"'" +
" AND coursenumber = (SELECT coursenumber "+"FROM courseuom WHERE coursename = '"+obj1+"') " ;
try {
statement = con.prepareStatement(sql) ;
int rs = statement.executeUpdate() ;
txtcnum.setText(" ") ;
txtdaysoftheweek.setText(" ") ;
txttime.setText(" ") ;
txtlocation.setText(" ") ;
txtcredithours.setText(" ") ;
chkopen.setSelected(false);
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// refresh the jlist
DefaultListModel listModel = new DefaultListModel();
try{
statement = con.prepareStatement("SELECT coursenumber "+"FROM courseofferinguom WHERE professorid = '"+teacher.getTeacherID()+"'");
ResultSet rs1 = statement.executeQuery();
if (rs1 != null) {
while(rs1.next())
{
statement = con.prepareStatement("SELECT coursename "+"FROM courseuom WHERE coursenumber = '"+rs1.getString(1)+"'");
ResultSet rs2 = statement.executeQuery();
if (rs2 != null) {
while(rs2.next())
{
listModel.addElement(rs2.getString(1)) ;
}
}
}
}
lstcourses.setModel(listModel) ;
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
// clears the textboxes.
}
}
However, as you can noticed, there is a valueChanged listener. So when i delete the item, it is no longer in the jlist, hence an exception is created. The delete works fine though, i just want to eliminate the exception.

You may do a null check before proceeding further in your valueChanged(ListSelectionEvent) listener, as the value would be null when the record is deleted.
There could be better solutions available though.

Related

How to deal with multiple queries in a java servlet

I'm trying to send an increase count variable of a picture (which is increased by just increasing +1 everytime a new session hits a picture). I'm getting the following error message however, i'm checking for an empty result set. My thought process is that I can try to select the picturesNo that has been called and if it can't find that pictureNo we simply insert the first count to the table, and if it can find it, we then update this.
Error message:
"SQLException: Illegal operation on empty result set."
Code to increase the count for the session
HttpSession session = request.getSession() ;
Integer counter = (Integer) session.getAttribute("counter");
String accCount = (String) session.getAttribute("attributeKey") ;
String url = "http://localhost:8080/techfore";
String encodedURL = url + ";jsessionid=" + request.getSession().getId();
if (accCount == null || encodedURL == null) { // New session?
response.sendRedirect("/techfore/WelcomePage");
}
else{
if(counter == 0) {
counter = new Integer(counter.intValue() + 1);
session.setAttribute("counter", counter);
}
}
Utilities.initalCount(out, pictureName, counter);
Code to run the queries
public static void initalCount(PrintWriter out, String pictureName, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
}
try {
Statement stmt = con.createStatement();
String query0;
ResultSet rs1;
query0="SELECT PictureNo FROM Statistics WHERE PictureNo = (SELECT PictureNo FROM Pictures WHERE ShortName = '"+pictureName+"')";
rs1 = stmt.executeQuery(query0);
if(rs1.next()){
//yes exist
String description = rs1.getString("Description");
int pictureNo = rs1.getInt("PictureNo");
IncreaseCount(out, pictureNo, accessCount);
}
else {
//if rs is null insert
int pictureNo = rs1.getInt("PictureNo");
AddCount(out, pictureNo, accessCount);
}
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
public static void AddCount(PrintWriter out, int pictureNo, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query="INSERT INTO Statistics VALUES "+pictureNo+","+accessCount+" ";
stmt.executeUpdate(query);
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
public static void IncreaseCount(PrintWriter out, int pictureNo, int accessCount) {
Connection con = null;
try { // Connect to the database
con = openConnection(out);
}
catch (Exception e) { // Failed to open the connection
out.println("<P>" + e.getMessage());
return;
}
try {
Statement stmt = con.createStatement();
String query;
ResultSet rs1;
query="UPDATE Statistics SET AccessCount = "+accessCount+" + 1 WHERE PictureNo = "+pictureNo+"";
stmt.executeUpdate(query);
stmt.close() ;
}
catch(SQLException ex) {
out.println("<P>SQLException: " + ex.getMessage()) ;
}
}
New insert
query="INSERT INTO Statistics VALUES (SELECT PictureNo FROM Pictures WHERE FileName = '"+pictureName+"'),"+accessCount+" ";

Select query showing wrong result

I am tring to check whether a data is available or not in database table.if not it will insert the data. But in first button click it works perfectly. by when i try to click the button again with the same value it gets inserted into the table. please help someone
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
try {
// TODO add your handling code here:
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
ArrayList<String> list = new ArrayList<>();
Object obj[] = null;
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/cem?useSSL=false", "root", "123");
//here stu is database name, root is username and password
Statement stmt = con.createStatement();
String pn = "select gname from games where gname='" + jTextField1.getText() + "'";
ResultSet rsPn = stmt.executeQuery(pn);
System.out.println(rsPn.next());
if (rsPn.next() == false) {
String q = ("insert into games(gid,gname) values(NULL,'" + jTextField1.getText() + "')");
int i = 0;
i = stmt.executeUpdate(q);
if (i > 0) {
System.out.println("success");
list.add(jTextField1.getText());
obj = list.toArray();
model.addRow(obj);
} else {
System.out.println("stuck somewhere");
}
StudentDetails.details();
jTextField1.setForeground(Color.BLACK);
stmt.close();
con.close();
} else {
jTextField1.setForeground(Color.red);
System.out.println("Name Already exist");
}
} catch (SQLException ex) {
Logger.getLogger(InsertPanel.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex) {
Logger.getLogger(InsertPanel.class.getName()).log(Level.SEVERE, null, ex);
}
}
You're calling next() twice:
System.out.println(rsPn.next());
if (rsPn.next() == false) {
The second call will return false even if there's a row already (though it should work once there are two or more rows). Use a variable instead:
boolean hasNext = rdPn.next();
System.out.println(hasNext);
if (!hasNext) {

How to copy selected items from one array to another?

Is there any way to create an array from another?, In my case I have a list, this list has checkboxes, each row, until now I can get the value of the checkboxes checked. Now my question is: Can I get those checkbox values and make another array from them?
if (accion.equalsIgnoreCase("agregar")) {
List<Directorio> listaDirectorio = DirectorioDAO.getListDirectorio(request.getParameter("a_selectCta"));
request.setAttribute("a_listaDirectorio", listaDirectorio);
String select[] = request.getParameterValues("a_checkCta");
for (int i = 0; i < select.length; i++) {
directorio = DirectorioDAO.getDirectorio(Integer.parseInt(select[i]));
System.out.println(select[i]);
System.out.println(directorio);
}
request.setAttribute("a_accion","agregar");
}
getDirectorio Method:
public static Directorio getDirectorio(int idDirectorio) {
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
Directorio directorio=null;
try {
connection = ConnectionDBM.getConnection();
if (connection != null) {
String sql = " SELECT id_directorio, id_ctahabiente, nombre_completo,cargo, calle_numero, "
+ " colonia, delegacion, CP, estado, telefono1, telefono2, ext1, ext2, correo, "
+ " observaciones, tipo, confirmado, principal, fechaModificacion "
+ " FROM DIRECTORIO WHERE id_directorio = ? ";
statement = connection.prepareStatement(sql);
statement.setInt(1, idDirectorio);
rs = statement.executeQuery();
if(rs.next()) {
directorio= new Directorio();
directorio.setIdDirectorio(rs.getInt("id_directorio"));
directorio.setIdCtahabiente(rs.getString("id_ctahabiente"));
directorio.setNombreCompleto(rs.getString("nombre_completo"));
directorio.setCargo(rs.getString("cargo"));
directorio.setCalleNumero(rs.getString("calle_numero"));
directorio.setColonia(rs.getString("colonia"));
directorio.setDelegacion(rs.getString("delegacion"));
directorio.setCP(rs.getString("CP"));
directorio.setEstado(rs.getString("estado"));
directorio.setTelefono1(rs.getString("telefono1"));
directorio.setTelefono2(rs.getString("telefono2"));
directorio.setExt1(rs.getString("ext1"));
directorio.setExt2(rs.getString("ext2"));
directorio.setCorreo(rs.getString("correo"));
directorio.setObservaciones(rs.getString("observaciones"));
directorio.setTipo(rs.getString("tipo"));
directorio.setConfirmado(rs.getBoolean("confirmado"));
directorio.setPrincipal(rs.getBoolean("principal"));
directorio.setFechaModificacion(rs.getDate("fechaModificacion"));
}
}
} catch (SQLException e) {
logger.error("getRegControl: ", e);
throw new RuntimeException(e);
} catch (Exception e) {
logger.error("getRegControl: ", e);
throw new RuntimeException(e);
} finally {
try {
statement.close();
} catch (Exception e) {
}
try {
rs.close();
} catch (Exception e) { }
try {
if (connection != null && !connection.isClosed())
connection.close();
} catch (Exception e) {}
}
return directorio;
}
In answer to your question you can aither by using a collection and using an addAll method or by using System.arrayCopy
But to be honest why does not change you query so that in it queries for all selected ids.
SELECT id_directorio, id_ctahabiente, nombre_completo,cargo, calle_numero, "
+ " colonia, delegacion, CP, estado, telefono1, telefono2, ext1, ext2, correo, "
+ " observaciones, tipo, confirmado, principal, fechaModificacion "
+ " FROM DIRECTORIO WHERE id_directorio IN ?
And then you will speed up your query and have cleaner code.
see https://stackoverflow.com/questions/13254133/jdbc-prepared-statement-how-to-set-a-list

Getting SQL error 1078 Before start of result set in Java program [duplicate]

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 5 years ago.
I have a Java method that is supposed to get column values from one MySQL row and create a string with the values. When run, it generates a SQL error 1078 "Before start of result set."
Here is the the class in which the error is occuring (Problem is in listPosesInSection method:
/** Class used to access the database */
import java.sql.*;
import java.util.ArrayList;
import javax.swing.JOptionPane;
public class YogaDatabaseAccess {
String dbUrl = "jdbc:mysql://localhost/yoga";
private Connection connection;
private ResultSet rset;
private ResultSetMetaData rsMetaData;
private Statement statement;
private PreparedStatement pStatementAll = null;
private PreparedStatement pStatementPartial = null;
// Strings for queries and updates
String strListPosesNotPrimary;
String strInsertNewClass;
String strInsertNewSection;
String strInsertNewPose;
String strUpdateClass;
String strUpdateSection;
String strUpdatePose;
String strArrangePoseOrder;
private String[] poseArray;
// Constructor
YogaDatabaseAccess() {
connectToDatabase();
}
// Method that connects to database
private void connectToDatabase() {
try {
connection = DriverManager.getConnection(dbUrl, "Kyle", "Kullerstrand#2");
System.out.println("Database connected");
}
catch(SQLException e) {
System.out.println(e.getMessage());
}
}
// Query that returns lists to be used with combo boxes
public String listForBoxes(String listName) {
// List to be returned
String strList = "";
// Determine name of the database table for this list
String listTableName;
if (listName == "pose")
listTableName = listName + "s";
else if (listName == "class")
listTableName = listName + "es";
else
listTableName = listName;
// Determine the database column name for this list
String listColumnName = listName + "_name";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT " + listColumnName + " FROM " + listTableName +
" ORDER BY " + listColumnName);
while (rset.next()){
strList = strList + rset.getString(listColumnName) + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns list of primary poses for a section
public String listPrimaryPoses(String sectionName) {
// List to be returned
String strList = "";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT pose_name FROM poses WHERE primarily_suitable_for = '" + sectionName +
"' OR primarily_suitable_for = 'Anything' ORDER BY pose_name");
while (rset.next()){
strList = strList + rset.getString("pose_name") + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns list of secondary poses for a section
public String listSecondaryPoses(String sectionName) {
// List to be returned
String strList = "";
// Run the query
try {
statement = connection.createStatement();
rset = statement.executeQuery("SELECT DISTINCT pose_name FROM poses WHERE sometimes_suitable_for = '" + sectionName + "' ORDER BY pose_name");
while (rset.next()){
strList = strList + rset.getString("pose_name") + ", ";
}
} catch (SQLException e) {
e.printStackTrace();
}
return strList;
}
// Query that returns the poses within a specific section
public String listPosesInSection(String tableName, String sectionName) {
String strList;
StringBuilder strBuilderList = new StringBuilder("");
// Run the query
try {
statement = connection.createStatement();
// Query will collect all columns from one specific row
rset = statement.executeQuery("SELECT * FROM " + tableName + " WHERE " + tableName + "_name = '" + sectionName + "'");
while (rset.next()) {
for (int i = 2; i <= countColumnsInTable(tableName); i++) // First value (0) is always null, skip section name (1)
if (rset.getString(i) != null) // If column has a value
strBuilderList.append(rset.getString(i) + "\n");
}
} catch (SQLException e) {
e.printStackTrace();
}
strList = strBuilderList.toString();
return strList.replaceAll(", $",""); // Strips off the trailing comma
}
// Insert statement that inserts a new class into the classes table
public void insertNewClass(String className) {
/** String insert = "INSERT INTO poses (pose_name, primarily_suitable_for, sometimes_suitable_for) values(?, ?, ?)";
System.out.println("About to create the prepared statement");
// Run the insert
try {
pStatement = connection.prepareStatement(insert);
// statement.execute("INSERT IGNORE INTO poses VALUES ('" + poseName + "', '" + suitableFor + "', '" + suitableForSometimes + "')");
pStatement.setString(1, poseName);
pStatement.setString(2, suitableFor);
pStatement.setString(3, suitableForSometimes);
System.out.println("Created the prepared statement");
// execute query, and return number of rows created
pStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} */
}
// Insert statement that inserts a new pose into poses table
public void insertNewPose(String poseName, String suitableFor, String suitableForSometimes) {
String insertAll = "INSERT INTO poses (pose_name, primarily_suitable_for, sometimes_suitable_for) values(?, ?, ?)";
String insertPartial = "INSERT INTO poses (pose_name, primarily_suitable_for) values(?, ?)";
// Run the insert
try {
if (suitableForSometimes == "NULL") { // Insert statement contains a null value for sometimes suitable column
pStatementPartial = connection.prepareStatement(insertPartial);
pStatementPartial.setString(1, poseName);
pStatementPartial.setString(2, suitableFor);
pStatementPartial.executeUpdate();
} else { // Insert statement contains values for all three columns
pStatementAll = connection.prepareStatement(insertAll);
pStatementAll.setString(1, poseName);
pStatementAll.setString(2, suitableFor);
pStatementAll.setString(3, suitableForSometimes);
pStatementAll.executeUpdate();
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "This pose already exists.");
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "An unknown error in the yoga design program has occurred.");
}
}
}
// Insert statement that inserts a new section into warmup, work or restore sections
public void insertNewSection(String sectionType, String sectionName, ArrayList<String> poses) {
System.out.println("insertNewSection method was called");
int maxColumns = countColumnsInTable(sectionType);
poseArray = new String[poses.size()];
poseArray = poses.toArray(poseArray);
if (poseArray.length == 0)
JOptionPane.showMessageDialog(null, "There are no poses in this section. Please add poses.");
// Create a list of columns of the table for the INSERT statement
StringBuilder columns = new StringBuilder(sectionType + "_name");
for (int c = 1; c < maxColumns; c++)
columns.append(", pose_" + c);
// Create a string list of poses, separated by commas, from the array
StringBuilder values = new StringBuilder();
values.append("'" + poseArray[0] + "'");
for (int v = 1; v < poseArray.length - 1; v++)
values.append(", '" + poseArray[v] + "'");
// make sure query uses correct number of columns by padding the query with NULL
for (int i = poseArray.length; i < maxColumns; i++)
values.append(", NULL");
String posesToAddToSection = values.toString();
// The string containing the entire insert statement
String insert = "INSERT INTO " + sectionType + " (" + columns + ") VALUES ('" + sectionName + "', " + posesToAddToSection + ")";
// Run the insert
try {
statement = connection.createStatement();
statement.executeUpdate(insert);
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "An error in the yoga design program has occurred. SQLException: " +
e.getMessage() + ":" + e.getSQLState());
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
JOptionPane.showMessageDialog(null, "An unknown error in the yoga design program has occurred.");
}
}
}
// Statement that deletes rows from tables
public void deleteRow(String tableName, String columnName, String rowName) {
String delete = "DELETE FROM " + tableName + " WHERE " + columnName + " = '" + rowName + "'";
// Run the insert
try {
statement = connection.createStatement();
statement.executeUpdate(delete);
System.out.println("Delete statement was run on Java's end.");
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage() + ":" + e.getSQLState());
JOptionPane.showMessageDialog(null, "Sorry, something went wrong: SQLException: " +
e.getMessage() + ":" + e.getSQLState());
} finally {
SQLWarning w;
try {
for (w = connection.getWarnings(); w != null; w = w.getNextWarning())
System.err.println("WARNING: " + w.getMessage() + ":" + w.getSQLState());
} catch (SQLException e) {
e.printStackTrace();
}
}
}
// Method for getting the number of columns in a table using metadata
public int countColumnsInTable(String sectionType) {
int count = 16;
try {
// System.out.println(sectionType);
statement = connection.createStatement();
rset = statement.executeQuery("SELECT * FROM " + sectionType);
rsMetaData = rset.getMetaData();
count = rsMetaData.getColumnCount();
// System.out.println("Column count is " + count);
} catch (SQLException e) {
e.printStackTrace();
}
return count;
}
// Close the database and release resources
public void closeDatabase() {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
And here is the beginning of the error list:
java.sql.SQLException: Before start of result set
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:855)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5773)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5693)
at YogaDatabaseAccess.listPosesInSection(YogaDatabaseAccess.java:125)
at YogaSectionDesigner$5.actionPerformed(YogaSectionDesigner.java:229)
May be you can check this out:
ResultSet exception - before start of result set
Had the same Problem. Solved it that way.

PL/SQL/Java - SQL Selects, for Loops, if statements and Lists

Right then, I've created an application to create a new booking for a student on a route.
This should them calculate the collision times using a database containing these times.
e.g. Student books an exam for 12:00, program will check for any other tests around that time, it will then check collision times, and if there is a collision it will add 5 minutes to the start time and try again. That's what I'm aiming for.
I know this is far from perfect or correct, but that's why I'm here.
BOOKING CLASS
public class Booking
{
private int bookingId;
private String route;
private int startTime;
private String bookingDate;
public Booking()
{
bookingId = 0000;
route = "No Route Entered";
startTime = 0000;
bookingDate = "No Date entered";
}
public int getBookingId()
{
return bookingId;
}
public String getRoute()
{
return route;
}
public int getStartTime()
{
return startTime;
}
public String getBookingDate()
{
return bookingDate;
}
public void setBookingId(int bookingId)
{
this.bookingId = bookingId;
}
public void setRoute(String route)
{
this.route = route;
}
public void setStartTime(int startTime)
{
this.startTime = startTime;
}
public void setBookingDate(String bookingDate)
{
this.bookingDate = bookingDate;
}
public Booking(int bookingId, String route, int startTime, String bookingDate)
{
setBookingId(bookingId);
setRoute(route);
setStartTime(startTime);
setBookingDate(bookingDate);
}
public String toString()
{
return "BookingId: " + getBookingId() + "\nRoute: " + getRoute() + "\nStart Time: " + getStartTime() +
"\nBooking Date: " + getBookingDate();
}
}
MAIN CLASS
import java.sql.*;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) throws SQLException {
//<editor-fold defaultstate="collapsed" desc="Creates new Student and booking">
Student s1 = new Student();
Booking b1 = new Booking();
s1.setStudentId(Integer.parseInt(JOptionPane.showInputDialog("Enter ID for Student: [0001]")));
s1.setFname(JOptionPane.showInputDialog("Enter first name of Student: "));
s1.setLname(JOptionPane.showInputDialog("Enter last name of Student: "));
s1.setAddress(JOptionPane.showInputDialog("Enter address for Student: "));
s1.setPhoneNo(JOptionPane.showInputDialog("Enter phone number for Student: "));
s1.setOtherDetails(JOptionPane.showInputDialog("Enter other details for Student: [Glasses?]"));
b1.setBookingId(0002);
b1.setStartTime(Integer.parseInt(JOptionPane.showInputDialog("Enter Start time for Booking: [1200]")));
b1.setBookingDate(JOptionPane.showInputDialog("Enter Date for Booking: [01-JAN-12]"));
int records = 0;
List <Booking> allBookings = new ArrayList<Booking>();
allBookings.add(b1);
for(Booking b:allBookings) {
JOptionPane.showMessageDialog(null, b1.getStartTime());//Get Start Time from user
//<editor-fold defaultstate="collapsed" desc="To select max time of all routes">
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//load the oracle driver...needs to be in classes folder in jre folder
} catch (ClassNotFoundException e) {
System.out.println(
" Can't find class oracle.jdbc.driver.OracleDriver");
System.exit(1);
}
Connection conn = null;
//new connection object
Statement stmtMax = null;
//new statemnt object
ResultSet maxTime = null;
//new record set object
try {
conn = DriverManager.getConnection("jdbc:oracle:thin:#oracle.tralee.ie:1521:orcl",
"*", "*");
stmtMax = conn.createStatement();
// create the statement for this connection
//</editor-fold>
maxTime = stmtMax.executeQuery(
"SELECT MAX(LENGTH) FROM ROUTE");
// get the results of select query and store in recordset object
while (maxTime.next()) {
// move to first/next record of recordset
JOptionPane.showMessageDialog(null, "Check: Max time of all routes: " + maxTime.getString(1));
// output next record using string format
}
//<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
maxTime.close();
maxTime = null;
stmtMax.close();
stmtMax = null;
conn.close();
conn = null;
} catch (SQLException e) {
System.out.println(" A SQL error: " + e.getMessage());
} finally {
if (maxTime != null) {
try {
maxTime.close();
} catch (SQLException ignore) {
}
}
if (stmtMax != null) {
try {
stmtMax.close();
} catch (SQLException ignore) {
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException ignore) {
}
}
}
// </editor-fold>
//<editor-fold defaultstate="collapsed" desc="To select all bookings within a time">
try { Class.forName("oracle.jdbc.driver.OracleDriver");
//load the oracle driver...needs to be in classes folder in jre folder
} catch (ClassNotFoundException e) {
System.out.println(
" Can't find class oracle.jdbc.driver.OracleDriver");
System.exit(1);
}
ERROR -
Connection conn2 = null;
//new connection object
Statement stmtTime = null;
//new statemnt object
ResultSet withinTime = null;
//new record set object
try {
conn2 = DriverManager.getConnection("jdbc:oracle:thin:#oracle.tralee.ie:1521:orcl",
"*", "*");
stmtTime = conn2.createStatement();
// create the statement for this connection
//</editor-fold>
withinTime = stmtTime.executeQuery(
"SELECT * FROM BOOKINGS WHERE" + b1.getStartTime() + "<=" + b1.getStartTime() + "-" + maxTime +
"AND" + b1.getStartTime() + ">=" + b1.getStartTime() + "+" + maxTime);
// get the results of select query and store in recordset object
JOptionPane.showMessageDialog(null, " Check: Bookings within a time: \n" + withinTime.getString(1));
while (withinTime.next()) {
// move to first/next record of recordset
JOptionPane.showMessageDialog(null, " Check: Bookings within a time: \n" + withinTime.getString(1));
// output next record using string format
}
//<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
withinTime.close();
withinTime = null;
stmtTime.close();
stmtTime = null;
conn2.close();
conn2 = null;
} catch (SQLException e) {
System.out.println(" A SQL error: " + e.getMessage());
} finally {
if (withinTime != null) {
try {
withinTime.close();
} catch (SQLException ignore) {
}
}
if (stmtTime != null) {
try {
stmtTime.close();
} catch (SQLException ignore) {
}
}
if (conn2 != null) {
try {
conn2.close();
} catch (SQLException ignore) {
}
}
}
//END OF ERROR
//<editor-fold defaultstate="collapsed" desc="To select all free routes">
try { Class.forName("oracle.jdbc.driver.OracleDriver");
//load the oracle driver...needs to be in classes folder in jre folder
} catch (ClassNotFoundException e) {
System.out.println(
" Can't find class oracle.jdbc.driver.OracleDriver");
System.exit(1);
}
Connection conn3 = null;
//new connection object
Statement stmtFreeR = null;
//new statemnt object
ResultSet freeRoute = null;
//new record set object
try {
conn3 = DriverManager.getConnection("jdbc:oracle:thin:#oracle.tralee.ie:1521:orcl",
"*", "*");
stmtFreeR = conn3.createStatement();
// create the statement for this connection
freeRoute = stmtFreeR.executeQuery(
" SELECT ROUTEID FROM Route MINUS SELECT ROUTEID FROM Booking ");
// get the results of select query and store in recordset object
while (freeRoute.next()) {
// move to first/next record of recordset
JOptionPane.showMessageDialog(null, "Check: Select all free RouteId's: " + freeRoute.getString(1));
//JOptionPane.showMessageDialog(null, " the answer is " + fRoutes);
// output next record using string format
}
//<editor-fold defaultstate="collapsed" desc="To randomize free routes">
//ERROR -- Does not do anything?
if( freeRoute != null) {
List RouteX = new ArrayList();
while (freeRoute.next()) {
RouteX.add(freeRoute.getString(1));
Collections.shuffle(RouteX);
JOptionPane.showMessageDialog(null, "Free routes list: " + RouteX);
}
}
else {
List RouteX = new ArrayList();
while (freeRoute.next()) {
RouteX.add(freeRoute.getString(1));
Collections.shuffle(RouteX);
JOptionPane.showMessageDialog(null,"Free routes list: " + RouteX);
}
}
//<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
freeRoute.close();
freeRoute = null;
stmtFreeR.close();
stmtFreeR = null;
conn3.close();
conn3 = null;
} catch (SQLException e) {
System.out.println(" A SQL error: " + e.getMessage());
} finally {
if (freeRoute != null) {
try {
freeRoute.close();
} catch (SQLException ignore) {
}
}
if (stmtFreeR != null) {
try {
stmtFreeR.close();
} catch (SQLException ignore) {
}
}
if (conn3 != null) {
try {
conn3.close();
} catch (SQLException ignore) {
}
}
}
//<editor-fold defaultstate="collapsed" desc="To count number of routes">
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//load the oracle driver...needs to be in classes folder in jre folder
} catch (ClassNotFoundException e) {
System.out.println(
" Can't find class oracle.jdbc.driver.OracleDriver");
System.exit(1);
}
Connection conn4 = null;
//new connection object
Statement stmtCountR = null;
//new statemnt object
// ResultSet countRoutes = null;
//new record set object
try {
conn4 = DriverManager.getConnection("jdbc:oracle:thin:#oracle.tralee.ie:1521:orcl",
"*", "*");
stmtCountR = conn4.createStatement();
// create the statement for this connection
//</editor-fold>
String sql = "SELECT COUNT(*) FROM ROUTE";
PreparedStatement prest = conn4.prepareStatement(sql);
ResultSet rs = prest.executeQuery();
while (rs.next()){
records = rs.getInt(1);
}
//System.out.println("Number of records: " + records);
// move to first/next record of recordset
JOptionPane.showMessageDialog(null, " Number of total routes: " + records);
//JOptionPane.showMessageDialog(null, " the answer is " + fRoutes);
// output next record using string format
//<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
// countRoutes.close();
//countRoutes = null;
rs.close();
rs = null;
stmtCountR.close();
stmtCountR = null;
conn4.close();
conn4 = null;
} catch (SQLException e) {
System.out.println(" A SQL error: " + e.getMessage());
}/* finally {
if (countRoutes != null) {
try {
countRoutes.close();
} catch (SQLException ignore) {
}
}*/
if (stmtCountR != null) {
try {
stmtCountR.close();
} catch (SQLException ignore) {
}
}
if (conn4 != null) {
try {
conn4.close();
} catch (SQLException ignore) {
}
}
}
//ERROR - for(r[X]) -- Looking to assign R with an incremented X value. i.e. R1, R2, R3 --
for(int X = 1; X < records; X++) {
for(r[X]) {
//<editor-fold defaultstate="collapsed" desc="To check if RX is in Collision Table">
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
//load the oracle driver...needs to be in classes folder in jre folder
} catch (ClassNotFoundException e) {
System.out.println(
" Can't find class oracle.jdbc.driver.OracleDriver");
System.exit(1);
}
Connection conn5 = null;
//new connection object
Statement stmtFindRx = null;
//new statemnt object
ResultSet checkRx = null;
//new record set object
try {
conn5 = DriverManager.getConnection("jdbc:oracle:thin:#oracle.tralee.ie:1521:orcl",
"*", "*");
stmtFindRx = conn5.createStatement();
// create the statement for this connection
checkRx = stmtFindRx.executeQuery(
"*********");
// get the results of select query and store in recordset object
while (checkRx.next()) {
// move to first/next record of recordset
JOptionPane.showMessageDialog(null, " the answer is " + checkRx.getString(1));
// output next record using string format
}
//<editor-fold defaultstate="collapsed" desc="Error handling for Select Statement">
checkRx.close();
checkRx = null;
stmtFindRx.close();
stmtFindRx = null;
conn5.close();
conn5 = null;
} catch (SQLException e) {
System.out.println(" A SQL error: " + e.getMessage());
} finally {
if (checkRx != null) {
try {
checkRx.close();
} catch (SQLException ignore) {
}
}
if (stmtFindRx != null) {
try {
stmtFindRx.close();
} catch (SQLException ignore) {
}
}
if (conn5 != null) {
try {
conn5.close();
} catch (SQLException ignore) {
}
}
}
}
}
ERROR - Then check if RX is = the route entered, if he same add 5mins on.
if(R[X].equals(b1.getRoute())) {
b1.setStartTime(b1.getStartTime() + 0005);
} else {
String strConn = "jdbc:oracle:thin:#oracle.tralee.ie:1521:orcl";
String strUser = "*";
String strPassword = "*";
try {
Driver drv = new oracle.jdbc.driver.OracleDriver();
DriverManager.registerDriver(drv);
Connection conn6 = DriverManager.getConnection(strConn, strUser, strPassword);
//code to execute commands...
//Booking Insert
String query1 = "INSERT INTO Booking(BOOKINGID, BOOKINGTYPE, LNAME, STARTTIME, " +
"BOOKINGDATE, HISTORY) VALUES (?, ?, ?, ?, ?)";
PreparedStatement pstmt1 = conn6.prepareStatement(query1);
pstmt1.setInt(1, b1.getBookingId());
pstmt1.setDouble(3, b1.getStartTime());
pstmt1.setString(4, b1.getBookingDate());
pstmt1.executeUpdate();
JOptionPane.showMessageDialog(null, "Booking Confirmed");
conn6.close();
}
catch(SQLException e) {
System.out.println(" A SQL error: " + e.getMessage());
}
}
}
}
The Last error I'm not too bothered about yet, and I know it's not good to create a new connection everytime and in a loop, I will sort this later. But for now, what I am asking is
1) Why won't this statement:
SELECT * FROM BOOKINGS WHERE" +
b1.getStartTime() + "<=" + b1.getStartTime() + "-" + maxTime +
"AND" + b1.getStartTime() + ">=" + b1.getStartTime() + "+" + maxTime);
return the bookings within the start time plus the max time of all routes? and how do I fix this?
2) How do I adjust this, so that when the select is called, and returns the values of all the Free unbooked routes, it will insert it into an List and shuffle the list and return the route value?
The select runs and returns the correct values, although this error appears:
ORA-00933: SQL command not properly ended
" SELECT ROUTEID FROM Route MINUS SELECT ROUTEID FROM Booking ");
while (freeRoute.next()) {
JOptionPane.showMessageDialog(null, "Check: Select all free RouteId's: " + freeRoute.getString(1));
}
if( freeRoute != null) {
List RouteX = new ArrayList();
while (freeRoute.next()) {
RouteX.add(freeRoute.getString(1));
Collections.shuffle(RouteX);
JOptionPane.showMessageDialog(null, "Free routes list: " + RouteX);
}
}
else {
List RouteX = new ArrayList();
while (freeRoute.next()) {
RouteX.add(freeRoute.getString(1));
Collections.shuffle(RouteX);
JOptionPane.showMessageDialog(null,"Free routes list: " + RouteX);
}
}
And 3) This for statement, I want it to assign R with the X value, and basically say
for each R[X Value] then the body of the for statement?
for(int X = 1; X < records; X++) {
for(r[X]) {
I know I'm asking a lot here, but if someone could shed some light on what I need to change to get these things firing, it be very grateful.
EDIT:
BOOKINGS TABLE
CREATE BOOKING
(
BOOKINGID NUMBER(4,0),
STARTTIME NUMBER(4,0),
BOOKINGDATE DATE,
EXAMINERID NUMBER(4,0),
STUDENTID NUMBER(4,0),
ROUTEID NUMBER(4,0),
CONSTRAINT BOOKING_PK PRIMARY KEY (BOOKINGID)
CONSTRAINT EXAMINER_FK FOREIGN KEY (EXAMINERID) REFERENCES EXAMINER,
CONSTRAINT STUDENT_FK FOREIGN KEY (STUDENTID) REFERENCES STUDENT,
CONSTRAINT ROUTE_FK FOREIGN KEY (ROUTEID) REFERENCES ROUTE);
Just first off I think you should look at the time functions of mysql. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html#function_addtime more specifically the addtime function.
I am not sure exactly what type is the column against which you are validating but the query does not seems to validate that column
SELECT * FROM BOOKINGS WHERE" + b1.getStartTime() + "<=" + b1.getStartTime() + "-" + maxTime + "AND" + b1.getStartTime() + ">=" + b1.getStartTime() + "+" + maxTime);
What are the bookings table columns for start time. Your query at run current will look like this:
select * from bookings where12<=12-5and12>=12+5
I would highly recommand you first use a string to assign your query string and use the console to output the statement so you can debug the statement easily without the rest of the application. I would also recommand you read about parameterized query because you are passing the user input right into the query and that is a big door open for SQL injection. See this link:
http://docs.oracle.com/javase/tutorial/jdbc/basics/prepared.html
If you post you bookings table schema I am sure we can help you make up the right query based on your requirements.
EDIT
This might not be exactly the query you required but it will give you a good starting point. I highly suggest you debug the query first in sql plus of whatever tool you are using.
PreparedStatement prest;
Connection conn2 = DriverManager.getConnection("jdbc:");//set you jdbc url
String sql = "select * from bookings where bookingdate = ? and starttime between ? and ?";
prest = con.prepareStatement(sql);
prest.setDate(1,b1.getBookingDate());
prest.setInt(2,b1.getStartTime()-5);
prest.setInt(3,b1.getStartTime()+5);
ResultSet rs1 = prest.executeQuery();
while(rs1.hasNexT())
//extract data here

Categories

Resources