public ArrayList<Booking> getAllBookings(){
ArrayList<Booking> list = new ArrayList<Booking>();
int rowCount = 0;
try {
stmt = connection.createStatement();
String sql = "SELECT * FROM Bookings";
ResultSet rows = stmt.executeQuery(sql);
rows.last();
System.out.println("Row Count "+rows.getRow());
rows.beforeFirst();
connection.commit();
while (rows.next()){
Booking b = new Booking();
otherStuff();
list.add(b);
rowCount++;
}
stmt.close();
rows.close();
} catch (Exception e) {
}
System.out.println("There were " +rowCount + " records.");
return list;
}
Why do I not get any rows returned? I am connecting using this:
public static Connection dbConnect(){
try {
Class.forName("org.sqlite.JDBC");
Connection connection = DriverManager.getConnection("jdbc:sqlite:D:/test/test_db.sqlite3");
System.out.println("Connection Succesful");
return connection;
} catch (Exception e) {
System.out.println(e);
return null;
} }
When running SQLite Studio my query returns the correct results, but here my output on console is:
Connection Succesful
(Row Count + rows.getRow() is not printing here for some reason)
There were 0 records.
Related
I'm using a MySQL database to hold information for my reminder application in Java. I'm trying to pull the information out and store it in an array and the compare each element of the array to an updating current timestamp. The issue is the code I have gives a nullpointer exception and I can't figure out why. It works when the LocalDateTime isn't an array but the moment I turn it into an array it throws the error. It also demands I initialize it to null over anything else.
Thoughts on how I can fix this? Any help is appreciated.
Here's the method in question.
public static LocalDateTime[] getReminderTime()
{
String SQL = "SELECT r_dateTime FROM reminder_database.reminder;";
LocalDateTime reminderTime[] = null;
try
{
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
for(int i = 0; rs.next(); i++)
{
reminderTime[i] = rs.getTimestamp(1).toLocalDateTime();
}
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception thrown with getReminderTime --> " + e + e.getStackTrace());
}
return reminderTime;
}
Heres the exception thrown
Exception thrown with getReminderTime --> java.lang.NullPointerException[Ljava.lang.StackTraceElement;#6dfc1e5f
Exception thrown with getReminderTime --> java.lang.NullPointerException[Ljava.lang.StackTraceElement;#3b2da18f
Found a solution.
I needed to initialize a size for the array in order to fill it. So I created another method that went through all the elements and gets the size.
Here's the code.
public static LocalDateTime[] getReminderTime()
{
String SQL = "SELECT r_dateTime FROM reminder_database.reminder;";
LocalDateTime reminderTime[] = null;
reminderTime = new LocalDateTime[getSizeOfRs()];
try
{
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
if(rs.isBeforeFirst())
{
for(int i = 0; rs.next(); i++)
{
reminderTime[i] = rs.getTimestamp(1).toLocalDateTime();
}
}
rs.close();
stmt.close();
conn.close();
}
catch(Exception e)
{
System.out.println("Exception thrown with getReminderTime --> " + e + e.getStackTrace());
}
return reminderTime;
}
and the get rs size
public static int getSizeOfRs()
{
String SQL = "SELECT * FROM reminder_database.reminder;";
int size = 0;
try {
Connection conn = main.getConnection();
java.sql.Statement stmt;
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(SQL);
for(int i = 0; rs.next(); i++)
size++;
}
catch(Exception e)
{
System.out.println("Exception thrown with getSizeofRS --> " + e + e.getStackTrace());
}
return size;
}
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+" ";
So I want to be able to display 500 records at a time, commit and print that it has been displayed records 1 to 500 records have been committed. And than do the next 500 records and commit again until reached the maximum records which is over 20k records. I managed to get the first 500 records but I am stuck how can I commit them and in commit them and continue to get the next 500 records and so on.
public static void selectRecordsIcore() throws SQLException {
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
Statement statement = null;
String selectTableSQL = "SELECT profile_id, ingress_flag, egress_flag, ce_ingress_flag, ce_egress_flag from COS_PROFILE"
+ " WHERE profile_id >= ? AND profile_id <= ?;";
try {
dbConnection = getInformixConnection(); //connects to ICORE database
System.out.println("I am in the try");
//Gets the max profile_id record
statement = dbConnection.createStatement();
ResultSet r = statement.executeQuery("SELECT max(profile_id) AS rowcount FROM COS_PROFILE");
r.next();
int maxCount = r.getInt("rowcount");
System.out.println("COS_PROFILE table before update has " + maxCount + " row(s).");
preparedStatement = dbConnection.prepareStatement(selectTableSQL);
preparedStatement.setInt(1, 1);
preparedStatement.setInt(2, maxCount);
// execute select SQL statement
rs = preparedStatement.executeQuery();
updateRecordIntoBids();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (rs != null) {
rs.close();
}
if (statement != null) {
statement.close();
}
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database ICORE Connection is closed");
}
}
}
private static void updateRecordIntoBids() throws SQLException {
System.out.println("I am inside update method");
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
dbConnection = getOracleConnection(); //connects to BIDS database
String updateTableSQL =
"UPDATE traffic_profile_temp SET pe_ingress_flag = ?, "
+ " pe_egress_flag = ?,"
+ " ce_ingress_flag = ?,"
+ " ce_egress_flag = ? "
+ " WHERE traffic_profile_id = ? ";
preparedStatement = dbConnection.prepareStatement(updateTableSQL);
try {
int rowCount = 0;
while (rs.next() && rowCount < 500) {
// System.out.println("inside the while loop");
String ingressflag = rs.getString("ingress_flag"); //BIDS column is pe_ingress_flag
String egressflag = rs.getString("egress_flag"); //BIDS column is pe_egress_flag
String ceingressflag = rs.getString("ce_ingress_flag"); //BIDS column is ce_ingress_flag
String ceegressflag = rs.getString("ce_egress_flag"); //BIDS column is ce_egress_flag
int profileid = rs.getInt("profile_id"); //BIDS column is traffic_profile_id
preparedStatement.setString(1, ingressflag);
preparedStatement.setString(2, egressflag);
preparedStatement.setString(3, ceingressflag);
preparedStatement.setString(4, ceegressflag);
preparedStatement.setInt(5, profileid);
// System.out.println(updateTableSQL);
System.out.println("Record " +profileid +" is updated to traffic_profile_temp table!");
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
System.out.println(rowCount);
}
preparedStatement.executeBatch();
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
preparedStatement.close();
}
if (dbConnection != null) {
dbConnection.close();
System.out.println("Database BIDS Connection is closed");
}
}
}
update this part
while (rs.next() && rowCount < 500) {
with
while (rs.next()) {
and
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
System.out.println(rowCount);
with
// execute update SQL stetement
preparedStatement.addBatch();
rowCount++;
if(rowCount % 500 == 0){
preparedStatement.executeBatch();
}
System.out.println(rowCount);
This check if the rowCount can be divided by 500, execute the batch. Don't forget to execute the batch after all statements finish to execute the remaining batches which couldn't divided by 500 . for more details regarding batches
All of my database access methods have been working up until now. I have a string of n usernames separated by ";", and I want to make n separate select statements to check if the user is online or offline. However, when used, this method returns nothing (""). The database connection is working. Any solutions are welcome.
EDIT:
New method, still does not work:
public static String CheckOn(String users) {
String toreturn = "";
PreparedStatement stmt2 = null;
ResultSet rs2 = null;
try {
conn = Database.getDBConnection("test");
String sql = "SELECT name FROM sessions WHERE name=?";
stmt2 = conn.prepareStatement(sql);
String[] usarr = users.substring(1, users.length()).split(";");
for (int i = 0; i <usarr.length;i++){
if (usarr[i].equals("Empty")){
toreturn = toreturn + "-";
}
else{
stmt2.setString(1, usarr[i]);
rs2 = stmt2.executeQuery();
if (rs2.next()){
toreturn = toreturn + "y";
}
else{
toreturn = toreturn + "n";
}
rs2.close();
}
}
rs2.close();
stmt2.close();
conn.close();
} catch (SQLException se) {
se.printStackTrace();
} finally {
try {
if (stmt2 != null)
stmt2.close();
} catch (SQLException se2) {
}
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}
}
return toreturn;
}
I am writing a program that will take in a student ID and verify if that ID exists in a mysql table. If it does exist, I would like to take the entire row that it exists in and copy that row to another table. Currently the program will just copy all rows in a table to the other. Any help appreciated. I have inserted a snippet of code below.
try {
String compareText = IDField.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
Statement stmt1 = conn.createStatement();
ResultSet rs1 = stmt1.executeQuery("select * from students where LUID='"+IDField.getText()+"' ");
boolean isPresent = rs1.next();
if (isPresent)
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/simlab","root","password");
System.out.println("Connected to database");
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
if (rows == 0)
{
System.out.println("Don't add any row!");
}
else
{
System.out.println(rows + " row(s)affected.");
conn.close();
}
//System.out.println("Already exists!!");
}
You could all do that in a single SQL statement:
INSERT INTO <Dest-Table>
(SELECT * FROM <Src-Table> WHERE ID=?);
It will only copy rows that exist.
I suspect it's due to this line:
int rows = stmt1.executeUpdate("INSERT INTO skills(ID_Student,LUID_Student)SELECT ID, LUID FROM students");
As, if that line is parsed, the SELECT statement has no WHERE clause, and will therefore get every row, and therefore insert everything.
With Prepared statements
String sql = "INSERT INTO abc"
+ "(SELECT id1,id2 FROM pqr)";
ps1 = con.prepareStatement(sql);
int rs = ps1.executeUpdate();
if (rs > 0) {
update = true;
} else {
update = false;
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
try {
if (ps1 != null) {
ps1.close();
ps1 = null;
}
if (con != null) {
con.close();
con = null;
}
} catch (Exception e) {
}
}
return update;