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+" ";
Related
Everytime at around "composedLine = String.format("%s, %s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);"
it produces "INSERT INTO airport VALUES (, ABR, Aberdeen Regional Airport, Aberdeen"
instead of "INSERT INTO airport VALUES (ABR, Aberdeen Regional Airport, Aberdeen"
which causes a syntax error when I use executeupdate due to the "," before the ABR.
import java.io.*;
import java.sql.*;
import java.util.*;
public class UsaDelayFlight {
public static Connection connectToDatabase(String user, String password, String database) {
System.out.println("------ Testing PostgreSQL JDBC Connection ------");
Connection connection = null;
try {
String protocol = "jdbc:postgresql://";
String dbName = "";
String fullURL = protocol + database + dbName + user;
connection = DriverManager.getConnection(fullURL, user, password);
} catch (SQLException e) {
String errorMsg = e.getMessage();
if (errorMsg.contains("authentication failed")) {
System.out.println("ERROR: \tDatabase password is incorrect. Have you changed the password string above?");
System.out.println("\n\tMake sure you are NOT using your university password.\n"
+ "\tYou need to use the password that was emailed to you!");
} else {
System.out.println("Connection failed! Check output console.");
e.printStackTrace();
}
}
return connection;
}
public static void dropTable(Connection connection, String table) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("DROP TABLE IF EXISTS " + table);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static void createTable(Connection connection, String tableDescription) throws SQLException {
Statement st = null;
try {
st = connection.createStatement();
boolean result = st.execute("CREATE TABLE IF NOT EXISTS " + tableDescription);
} catch (SQLException e) {
e.printStackTrace();
}
st.close();
}
public static ResultSet executeQuery(Connection connection, String query) {
System.out.println("DEBUG: Executing query...");
try {
Statement st = connection.createStatement();
ResultSet rs = st.executeQuery(query);
return rs;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
public static int insertIntoTableFromFile(Connection connection, String table,
String filename) {
int numRows = 0;
String currentLine = null;
try {
BufferedReader br = new BufferedReader(new FileReader(filename));
Statement st = connection.createStatement();
// Read in each line of the file until we reach the end.
while ((currentLine = br.readLine()) != null) {
String[] values = currentLine.split(",");
System.out.println(Arrays.toString(values));
String composedLine = "INSERT INTO " + table + " VALUES (";
//String r = String.format("formatted values are %s", composedLine);
composedLine = String.format("%s, %s, %s, %s", composedLine,
values[0], values[1], values[2], values[3]);
System.out.println(composedLine);
//. . .
// Finally, execute the entire composed line.
numRows = st.executeUpdate(composedLine);
}
} catch (Exception e) {
e.printStackTrace();
}
return numRows;
}
// NOTE: You will need to change some variables from START to END.
public static void main(String[] argv) throws SQLException {
// START
// Enter your username.
String user = "";
// Enter your database password, NOT your university password.
String password = "";
/** IMPORTANT: If you are using NoMachine, you can leave this as it is.
*
* Otherwise, if you are using your OWN COMPUTER with TUNNELLING:
* 1) Delete the original database string and
* 2) Remove the '//' in front of the second database string.
*/
String database = "";
//String database = "";
// END
Connection connection = connectToDatabase(user, password, database);
if (connection != null) {
System.out.println("SUCCESS: You made it!"
+ "\n\t You can now take control of your database!\n");
} else {
System.out.println("ERROR: \tFailed to make connection!");
System.exit(1);
}
// Now we're ready to use the DB. You may add your code below this line.
createTable(connection, "delayedFlights (ID_of_Delayed_Flight varchar(15) not null, Month varchar(10), "
+ "DayofMonth int, DayofWeek int, DepTime timestamp, ScheduledDepTime timestamp, ArrTime int,"
+ "ScheduledArrTime timestamp, UniqueCarrier varchar(15) not null, FlightNum int, ActualFlightTime timestamp,"
+ "scheduledFlightTime timestamp, AirTime timestamp, ArrDelay timestamp, DepDelay timestamp, Orig varchar(15),"
+ "Dest varchar(15), Distance int, primary key (ID_of_Delayed_Flight), unique (UniqueCarrier));");
createTable(connection, "airport (airportCode varchar(15) not null, "
+ "airportName varchar(15), City varchar(15), State varchar(15), primary key (airportCode));");
insertIntoTableFromFile(connection, "airport", "airport");
String query = "SELECT * FROM delayedFlights;";
ResultSet rs = executeQuery(connection, query);
try {
while (rs.next()) {
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}
rs.close();
}
}
This code is a security vulnerability. Specifically, SQL injection. This is not how you do it.
The correct way also solves your problem in passing. Thus, solution: Do it the correct way, solves all your problems.
Correct way:
PreparedStatement ps = con.prepareStatement("INSERT INTO " + table + " VALUES (?, ?, ?, ?)");
ps.setString(1, values[0]);
ps.setString(2, values[1]);
ps.setString(3, values[2]);
ps.setString(4, values[3]);
ps.executeUpdate();
I have it set up where I can save my object information to a SQL database using this block of code:
public boolean add(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if (aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
sqlStr.append("INSERT INTO ");
sqlStr.append(ORDER_TABLE);
sqlStr.append(" (firstName, lastName, size, cheese, sausage, ham, total)");
sqlStr.append(" VALUES (?,?,?,?,?,?,?)");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString(), Statement.RETURN_GENERATED_KEYS);
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
if (rowCount == 1) {
ResultSet rs = statement.getGeneratedKeys();
if(rs.next()) {
aOrder.setId(rs.getInt(1));
}
success = true;
}
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot save pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Insert", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
What I am trying to do is change the total variable with an update to the object on the server. I dont have an error right now popping up but nothing is changing in my objects information. Here is my code with the update block:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
//TODO create the SQL and prepared statements to update an order in the database
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET firstName = ?, lastName = ?, size = ?, cheese = ?, sausage = ?, ham = ?, total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setString(1, aOrder.getFirstName());
statement.setString(2, aOrder.getLastName());
statement.setString(3, aOrder.getPizzaSize());
statement.setBoolean(4, aOrder.getCheese());
statement.setBoolean(5, aOrder.getSausage());
statement.setBoolean(6, aOrder.getHam());
statement.setDouble(7, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I have it set up that just the total variable will be changed by the time the update block of code will be ran. So I was trying to just call all the variables again in the hopes that it would change the total.
I get the same results with this update block of code:
public boolean update(PizzaOrder aOrder) {
boolean success = false;
PreparedStatement statement = null;
StringBuilder sqlStr = new StringBuilder();
int rowCount;
if(aOrder != null && dbConnect != null && dbConnect.isConnected()) {
try {
rowCount = aOrder.getId();
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ").append(rowCount);
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
rowCount = statement.executeUpdate();
}
catch (SQLException e) {
String prompt = e.getMessage()
+ " cannot update pizza order information for "
+ aOrder.getFullName();
JOptionPane.showMessageDialog(null, prompt, "SQL Server Error: Update", JOptionPane.ERROR_MESSAGE);
}
}
else if (aOrder == null) {
throw new NullPointerException("Pizza Order object is null");
}
else {
throw new IllegalStateException("Database is not connected");
}
return success;
}
I figured out my problem I had something elsewhere in my code blocking the update. This is the code that is working to update the mySQL database in this case:
try {
//TODO create the SQL and prepared statements to update an order in the database
sqlStr.append("UPDATE ");
sqlStr.append("pizzaorder ");
sqlStr.append("SET total = ? WHERE id = ?");
statement = dbConnect.getConnection().prepareStatement(sqlStr.toString());
statement.setDouble(1, aOrder.getTotal());
statement.setInt(2, aOrder.getId());
rowCount = statement.executeUpdate();
}
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 have been trying to insert data into DB using prepared statement but not able to run stmt.executeUpdate() The query will insert the field from the array which is declared below,The statement will set the values from the array.
long[] array = new long[100];
int[] devreg = new int[10];
int count = 0, index = 0;
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(Constants.DB_URL, Constants.USER, Constants.PASS);
// LogMgr.dblogger.info(name +" : Database connection established"); //connection passed
}
catch (Exception e)
{
LogMgr.dblogger.info("Cannot connect to database" + e.toString()); //connection failure
}
if (conn != null) //if connection passed or available
{ //checking device registration
String InsertQuery = " INSERT INTO `acc_dev_db`.`widhb` (`name`,`age`, `type`) VALUES ";
int needacomma = 0;
for (int i=0; i< noofMsg; i++)
{
long empid = array[(i*indexlength)+1];
try
{
Statement s = conn.createStatement ();
s.executeQuery ("SELECT `empid` FROM `acc_dev_db`.`ID` WHERE `widevid` = "+empid+";");
ResultSet rs = s.getResultSet ();
if (rs.next())
{
devstatus = true;
if(needacomma>0)
{
InsertQuery = InsertQuery + ",";
}
InsertQuery = InsertQuery + "(?,?,?,?)";
needacomma += 1;
devreg[j] = i;
j++;
LogMgr.dblogger.info("ID found registered : " + empid); //found device id in the device table. Known device
}
else
{
LogMgr.dblogger.info("ID found not registered : " + empid);
}
rs.close ();
s.close ();
}
catch (Exception e) {
LogMgr.dblogger.info("Database reading error \n" + e.toString() ); //database reading error
}
}
if (devstatus == true) //if device is registered or known device
{
InsertQuery = InsertQuery + ";";
java.sql.PreparedStatement stmt = conn.prepareStatement(InsertQuery);
int loc = 1;
for (count = 0;count < j; count++)
{
int position = (indexlength*devreg[count]);
stmt.setLong(loc, array[position]);
System.out.println( array[position]);
stmt.setDouble(loc + 1, array[position + 1]);
System.out.println( array[position+1]);
stmt.setTimestamp(loc + 2,dateconvert(2, array[position + 2]));
System.out.println( array[position+2]);
stmt.setLong(loc + 3, array[position + 3]);
System.out.println( array[position+3]);
loc += 4;
}
LogMgr.jmslogger.info(stmt.toString());
try{
stmt.executeUpdate();
LogMgr.dblogger.info(name +" : studentdata update successfull from dev : " + devaddress);
}
catch(SQLException e){
System.out.println("EXCEPTION MAN!!!");
}
conn.close ();
}
Current O/P:
12355419
3740073994
491504582
43690
EXCEPTION MAN!!!
You Should throw SqlException or use try-catch block and for manage SqlException
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.