The DataBase is Locked..inserting values in table using a Loop - java

I am making a restaurant management application in java using sqlite database. In application when order confirm button is pressed the application is supposed to insert into order table, insert into order dishes/Items and minuses the quantity of each ingredient used in dish that is added in an order..
When i tried following code it says "SQLExcption:The Database is Locked "
for (int i = 0; i < orderTable.getRowCount(); i++) {
pst = con.prepareStatement("select dishId from dishes where dishName = '" + orderTable.getValueAt(i, 1) + "'");
rs = pst.executeQuery();
int dishId = rs.getInt("dishId");
pst = con.prepareStatement("insert into orderDishes values(?,?,?)");
pst.setInt(1, currentOrderNumber);
pst.setInt(2, dishId);
pst.setInt(3, (int) orderTable.getValueAt(i, 0));
pst.executeUpdate();
pst = con.prepareStatement("select ingId , quantity from dishIng where dishId = '" + dishId + "'");
rs = pst.executeQuery();
while (rs.next()) {
ingReducedQuantity = rs.getInt("quantity");
ingId = rs.getInt("ingId");
pst1 = con1.prepareStatement("select qunatity from ingriedients where ingId = '" + ingId + "'");
rs1 = pst1.executeQuery();
previousQuantity = rs1.getInt("qunatity");
pst1.close();
rs1.close();
con1.commit();
newQuantity = previousQuantity - ingReducedQuantity;
// Here it gives exception
pst1 = con1.prepareStatement("update ingriedients set qunatity = '" + newQuantity + "' where ingId = '" + ingId + "'");
pst1.executeUpdate();
con1.commit();
}
}
I think exception comes in while loop before updating ingriedients table but i don,t know why..plz suggest some solution..

before every connection and statements you need to close any privious connection and statement
because sqlite does not support more than one active transactions, so before the first con1.prepareStatement (in the while loop ) in your code, close other previous connections and statements also, I mean pst, con, etc

Related

How can I print the column names from 3 tables joining JDBC? [duplicate]

This question already has answers here:
Retrieve column names from java.sql.ResultSet
(14 answers)
Closed 3 years ago.
I have a 3 tables I have joined this query executes and prints out the tables data.
try {
Connection conn = DriverManager.getConnection(DB_URL, USERNAME, PASSWORD);
System.out.println("Connected");
Statement st = conn.createStatement();
String query = "SELECT s.*, sup.name as supplierName , p.name as partName "+
"FROM supplies s "+
"INNER JOIN supplier sup on s.supplierNum = sup.supplierNum "+
"INNER JOIN parts p on s.partNum = p.partNum";
ResultSet rs = st.executeQuery(query);
while(rs.next()) {
System.out.println(rs.getString("supplierNum"));
System.out.println(rs.getString("partNum"));
System.out.println(rs.getString("quantity"));
System.out.println(rs.getString("supplierName"));
System.out.println(rs.getString("partName"));
space();
}
} catch(Exception ex) {
System.out.println(ex);
}
But I was trying to add the column names so instead of the console printing:
It would to print the column names cascaded
supplierNum: S1
partNum: P1
quantity: 300
name: Smith
part: Nut
As suggested in https://stackoverflow.com/a/696794/11226302
You need to get the ResultSet meta data to programmatically get your column names from db.
Else, you can manually enter the names as suggested in other answers.
while(rs.next()) {
System.out.println("Supplier Name " + rs.getString("supplierNum"));
System.out.println("Part Name "+rs.getString("partNum"));
System.out.println("Quantity "+ rs.getString("quantity"));
System.out.println("SupplierName "+rs.getString("supplierName"));
System.out.println("PartName "+rs.getString("partName"));
space();
}
You can of course hard-code the column names because you already know them.
If you want to get them programmatically, then use the ResultSetMetaData similar to this:
Connection connection = ...
try (PreparedStatement ps = connection.prepareStatement(QUERY)) {
ResultSet resultSet = ps.executeQuery();
// get the meta data from the result set
ResultSetMetaData rsMeta = resultSet.getMetaData();
// receive the column count
int columnCount = rsMeta.getColumnCount();
// iterate them (their indexes start at 1, I think)
for (int i = 1; i < columnCount + 1; i++) {
// and print the column name, the type and the type name
System.out.println(rsMeta.getColumnName(i)
+ " ("
+ rsMeta.getColumnType(i)
+ ", "
+ rsMeta.getColumnTypeName(i)
+ ")");
}
} catch ...
...
}
If you want to directly output the column in your while loop, then get the meta data before that loop
ResultSetMetaData rsMeta = rs.getMetaData();
and then, inside the loop do
System.out.println(rsMeta.getColumnName(1) + ": " + rs.getString("supplierNum"));
System.out.println(rsMeta.getColumnName(2) + ": " + rs.getString("partNum"));
System.out.println(rsMeta.getColumnName(3) + ": " + rs.getString("quantity"));
System.out.println(rsMeta.getColumnName(4) + ": " + rs.getString("supplierName"));
System.out.println(rsMeta.getColumnName(5) + ": " + rs.getString("partName"));
From a resultSet you can optain his metadata
ResultSetMetaData meta = rs.getMetaData();
int cols = meta.getColumnCount();
for (int i = 1; i <= cols; i++) {
String colName = meta.getColumnName(i);
System.out.printf("%s=%s\n", colName, rs.getString(i);
...
}

Java Embedded, after insert I cannot recheck if the row exists

I am inserting a row in Java Derby Embedded database. Immediately I am rechecking whether the row with the particular ID exists. The code I use works fine elsewhere in Sqlite3, MySql etc. But in Derby it throws an error, invalid cursor state, no current row.( But the row is added and exists) What is that I am doing wrong?
String sql="";
stmt = conn.createStatement();
sql = "INSERT INTO USERLIST (UserID,UserName,PaWord,RealName) " +
"VALUES (" + Nextam + ",'" + f1 + "','" + f2 + "','" + f3 + "')";
stmt.executeUpdate(sql);
stmt.close();
Thread.sleep(1000);
// rechecking
stmt = conn.createStatement();
rs = stmt.executeQuery( "SELECT * FROM USERLIST where UserID=" + Nextam + "" );
String nameR = rs.getString("RealName");
if(nameR.length() < 2){
System.out.println( "Seems like Error " + Nextam );
}else{
String infum=nameR + " Added as " + Nextam;
ShowLab(infum);
}
stmt.close();
conn.close();
You didn't call rs.next() after you performed the stmt.executeQuery() call.
Are you sure this code works on other systems?

java/sql comparing two ints

I have the following function and I am trying to compare the number of students enrolled in a class with the class max. If the number enrolled is greater than the class max, I want to return a message that says, "The Class if Full".
public static void classFullCheck() {
try {
String currentNumberInClassAsString = ("SELECT class_id, COUNT(*) FROM ClassSelector.student_x_class WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(currentNumberInClassAsString);
int currentNumberInClassAsInt = 0;
if(rs.next()){
currentNumberInClassAsInt = rs.getInt(1);
}
String classSizeAsString = ("SELECT class_size FROM ClassSelector.classes WHERE class_id = " + selectedClass);
rs = myStmt.executeQuery(classSizeAsString);
int classSizeAsInt = 0;
if(rs.next()){
classSizeAsInt = rs.getInt("class_size");
}
if (currentNumberInClassAsInt > classSizeAsInt){
System.out.println("Sorry, this class is Full!");
}
} catch (java.sql.SQLException SQL) {
SQL.printStackTrace();
}
}
I am inserting the classFullcheck() function into the addClass() function like this:
public static void addClass() {
try {
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes");
while (rs.next()) {
String availableClasses = rs.getString("class_id") + "\t" + rs.getString("class_name") + "\t" + rs.getString("description");
System.out.println(availableClasses);
}
System.out.println("Enter Class ID from Classes Listed Above to Join: ");
selectedClass = sc.nextLine();
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
System.out.println(innerJoin);
String student_x_classJoin = "INSERT INTO student_x_class" + "(student_id, student_name, class_id, class_name)" + "VALUES (?, ?, ?, ?)";
PreparedStatement pStmt = con.prepareStatement(student_x_classJoin);
pStmt.setString(1, user_entered_student_id);
pStmt.setString(2, userEnterIdAsName);
pStmt.setString(3, rs.getString("class_id"));
pStmt.setString(4, rs.getString("class_name"));
pStmt.executeUpdate();
System.out.println("Would you like to enroll " + userEnterIdAsName + " into another class? (Y/N)");
String addAdditionalClass = sc.nextLine();
if (addAdditionalClass.equalsIgnoreCase("Y")) {
addClass();
} else if (addAdditionalClass.equalsIgnoreCase("N")) {
return;
}
}
}
catch (java.sql.SQLException SQL) {
System.out.println("Wait, This Student is already enrolled in this class!");
}
}
I am currently just getting both messages printed out, even if a class is not full. Any suggestions would help a lot.
if (currentNumberInClassAsInt >= classSizeAsInt) {
String updateStatus = "Update ClassSelector.classes SET status = ? WHERE class_id = " + selectedClass;
PreparedStatement pStmt = con.prepareStatement(updateStatus);
pStmt.setString(1, "Closed");
pStmt.executeUpdate();
System.out.println("Sorry, this class is Full! Select a different Class:");
System.out.println("\nSign Up For a Class\n");
addClass();
}
I think you want this:
currentNumberInClassAsInt = rs.getInt(2);
instead of:
currentNumberInClassAsInt = rs.getInt(**1**);
I don't think the ResultSet is 0 based...
Also is rs a global variable because it looks like you are changing your ResultSet rs when you call classFullCheck(). You may not have what you think you do in the ResultSet...
rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass);
while (rs.next()) {
classFullCheck();//****************result set changed here******************
String innerJoin = (userEnterIdAsName + " has been added to " + rs.getString("class_name") + " " + rs.getString("class_id"));
You may think you have this: rs = myStmt.executeQuery("SELECT * FROM ClassSelector.classes WHERE class_id = " + selectedClass); in your result set but you change rs in classFullCheck(). You may want to store the data in a different object that way when you run another query you can still access the data.

Defaults if player doesn't already have gems

Follow up question from here
Here is my current code, I try to preform the check to see if they have any tokens and then set the tokens if they dont but it seems to just be running the code no matter if I set it or not.
#EventHandler
public void onJoin(PlayerJoinEvent event) throws SQLException {
Player player = event.getPlayer();
String name = player.getName();
Statement statement = connection.createStatement();
ResultSet res = statement.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + name + "';");
res.next();
int tokens = 0;
if (res.getString("PlayerName") == null) {
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO tokens (`PlayerName`, `tokens`) VALUES ('" + name + "', '0');");
tokens = 1000;
} else {
tokens = res.getInt("tokens");
}
player.sendMessage(tokens + " Tokens.");
}
The way you check for a row's existence is wrong. Take a look at your query:
"SELECT * FROM tokens WHERE PlayerName = '" + name + "'
If a player does not exist in the table, this query will return 0 rows, not a row with null for the player's name, like you're checking now. Instead, you should check if the ResultSet has a row:
ResultSet res = statement.executeQuery("SELECT * FROM tokens WHERE PlayerName = '" + name + "';");
int tokens = 0;
if (res.next()) {
Statement statement = connection.createStatement();
statement.executeUpdate("INSERT INTO tokens (`PlayerName`, `tokens`) VALUES ('" + name + "', '0');");
tokens = 1000;
} else {
tokens = res.getInt("tokens");
}

java.sql.SQLException: Before start of result set. Query within Result set loop how? [duplicate]

This question already has answers here:
ResultSet exception - before start of result set
(6 answers)
Closed 9 years ago.
I'm trying to create a query within a results set loop but I keep getting the error "Before start of result set". I've attempted many different methods but they keep coming up with the same error.
Can someone help me out here?
String insertSQL = "INSERT INTO MonthlyReportTable VALUES(NULL,"; //Primary Key.
String PlannetSchemeCode = "";
int ResponcibleAuthorityID = 0;
Statement stmt = ConnectionDetails.getNewConnectionPPARSDB().createStatement();
ResultSet resultsSet = stmt.executeQuery("SELECT * FROM planning_scheme");
Statement insideStatement = ConnectionDetails.getNewConnectionPPARSDB().createStatement();
//Loop though each planning scheme and create the data for each field.
while (resultsSet.next())
{
PlannetSchemeCode = "'" + resultsSet.getString("ps_code") + "'";
//Planning Scheme Primary Key
insertSQL += PlannetSchemeCode + ",";
/*
//Responsible Authority ID
insertSQL += "'" + String.valueOf(
ResponcibleAuthorityID = MySQLUtil.getResults(
ConnectionDetails.Database_Connection_PPARSDB,
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
)
.getInt("resp_authority_id")
) + "'";
*/
ResultSet insideResultsSet =
insideStatement.executeQuery(
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
);
//ERROR HERE, some reason results set is getting set wrong??
//Error here, this current results set is resetting the Results set.
ResponcibleAuthorityID = insideResultsSet.getInt("resp_authority_id");
//Total_Received_CM
//Add the rest of the values temporary.
int FeildsAdded = 3;
for(int i = 1 + FeildsAdded; i < 458; i++)
{
insertSQL += String.valueOf(0) + ",";
}
//Insert date and end SQL string.
insertSQL += "NOW()";
insertSQL += ")";
System.out.println(insertSQL);
//Do Insert in PPARS.
//stmt.executeQuery(insertSQL);
//Reset the SQL String for the new Row.
insertSQL = "INSERT INTO MonthlyReportTable VALUES(NULL,";
}
A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.
You need to call ResultSet#next() before you can read the returned data.
ResultSet insideResultsSet = insideStatement.executeQuery(
"SELECT resp_authority_id " +
"FROM resp_authority_to_ps " +
"WHERE ps_code = " + PlannetSchemeCode
);
if (insideResultsSet.next()) {
ResponcibleAuthorityID = insideResultsSet.getInt("resp_authority_id");
// etc...
}

Categories

Resources