What I am trying to do is get the values from a column in my SQL table, specifically a column named SubjectName. Once I have these values I want to create JButtons named for each value in the ResultSet. My current code connects to my database and as far as I can tell the query to the table also works, however when I attempt to generate and add these buttons to my display the try/catch only returns that my statement failed. The code causing the problem lies somewhere here:
try
(
Statement initializeDisplay = connect.createStatement()
){
ArrayList<String> buttonList = new ArrayList<String>();
try
{
ResultSet rs = initializeDisplay.executeQuery("SELECT SubjectName from subjectpacktable order by SubjectID");
buttonList = new ArrayList<String>();
while(rs.next())
{
buttonList.add(rs.getString(1));
}
ArrayList<JButton> listOfButtons = new ArrayList<JButton>();
for (int i=0; i < 10; i++)
{
String temp2 = rs.getString(l);
JButton button1 = new JButton(temp2);
listOfButtons.add(button1);
l++;
}
l = 0;
while(listOfButtons.get(l) != null)
{
JButton tempButton = listOfButtons.get(l);
AddCardPanel1.add(tempButton);
l++;
}
while(buttonList.get(l) != null)
{
System.out.println(buttonList.get(l));
l++;
}
l = 0;
}
catch(SQLException e1)
{
System.err.println("Initial Display Failed");
}} catch (SQLException e2)
{
System.err.println("Initial Display Failed");
}
I'm wondering if the problem lies in actually retrieving the values from the table or somewhere else in the code are values not being assigned properly. Any help is appreciated.
Instead of the while loop, do
for(int i=0;i<buttonList.size();i++)
{
System.out.println(listOfButtons.get(i).getText());
}
this should keep your index inside the array bounds
Thanks for the help everyone! I used #Dalton and #BartHofma's reccommendations and got the code up and running.
Here is the working code:
try
(
Statement initializeDisplay = connect.createStatement();
)
{
try
{
ResultSet rs = initializeDisplay.executeQuery("SELECT SubjectName from subjectpacktable order by SubjectID");
ArrayList<JButton> listOfButtons = new ArrayList<JButton>();
while(rs.next())
{
String temp2 = rs.getString("SubjectName");
JButton button1 = new JButton(temp2);
listOfButtons.add(button1);
l++;
}
for(int i=0;i<listOfButtons.size();i++)
{
JButton holderButton = listOfButtons.get(i);
final String SubjectString = listOfButtons.get(i).getText();
holderButton.addActionListener(new ActionListener(){
#Override
public void actionPerformed(ActionEvent e)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e1)
{
System.err.println("Connection Failed");
}
System.out.println("Driver Connected");
Connection connect = null;
try
{
connect = DriverManager.getConnection
("jdbc:mysql://localhost:3306/example","root","root1229");
}
catch (SQLException e1)
{
System.err.println("Connection Failed");
}
System.out.println("Database Connected");
String addCardStatement;
k++;
int cardID = 0;
cardID += k;
String cardFront;
String cardBack;
cardFront = JOptionPane.showInputDialog("What would you like to name the card?");
cardBack = JOptionPane.showInputDialog("What would you like to define the card as?");
addCardStatement = "INSERT INTO " + SubjectString + "VALUES (" + cardID + "," + SubjectString + "," + cardFront + "," + cardBack + ")";
try
{
Statement addStatement = connect.createStatement();
addStatement.executeUpdate(addCardStatement);
}
catch (SQLException e1)
{
System.err.println("Statement failed");
}
}});
AddCardPanel1.add(holderButton);
}
}
catch(SQLException e1)
{
System.err.println("Initial Display Failed");
e1.printStackTrace();
}} catch (SQLException e2)
{
System.err.println("Initial Display Failed");
e2.printStackTrace();
}
Related
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) {
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
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.
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
Im looking to create a for loop for R[X]
X is stated in a previous for loop
The syntax for a for loop isnt giving me any help to this at all.
r is a short for route, say it picks R1 that would correspond to a row in a database
so X can be 1,2,3 etc..
So is it possible to say For(R[X])?
CODE:
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.staff.ittralee.ie:1521:orcl",
"*", "*");
stmtFindRx = conn5.createStatement();
// create the statement for this connection
//</editor-fold>
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));
//JOptionPane.showMessageDialog(null, " the answer is " + fRoutes);
// 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) {
}
}
}
// </editor-fold>
}
}
Taking a guess at a possible answer to the question i think you're trying to ask ...
Assuming that R[X] will give you some sort of collection, perhaps you might be looking for:
foreach (Route route in R[X]) {