I can't add items to the database because of this apparently.
Not putting the entire code, hope you can understand.
import java.sql.Connection/Driver/ResultSet/SQLException/Statement;
public class Main {
public static void main(String[] args) {
Statement st = null;
ResultSet rs = null;
try(Connection conn = everything right here)){
if(conn != null) {
System.out.println("Success conn!");
String query = "INSERT INTO students (id, nome) VALUES (1, 'College Name')";
st = conn.createStatement();
rs = st.executeUpdate(query);
Giving me type mismatch: can't resolve int to ResultSet in
rs = st.executeUpdate(query);
// continuation of above code
while(rs.next()) {
System.out.println("\nRegistro");
System.out.println("id: " + rs.getInt(1));
System.out.println("nome: " + rs.getString(2));
}
rs.close();
st.close();
conn.close();
}
}
}
}
I want to retrieve all the name and the number of row from MySQL to java. So far I only able to retrieve the total row number but I only get the last name. What's wrong here ?
StaffManagement.java
adminAPI api= new adminAPI();
try {
int num= api.displayCheckBoxAndLabel();
String allName= api.displayName();
System.out.println(num+allName);
}
adminAPI
public int displayCheckBoxAndLabel() throws Exception // get the number of row
{
int count = 0;
String sql="Select count(*) AS adminID from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
count= rs.getInt("adminID");
}
ps.close();
rs.close();
conn.close();
return count ;
}
public String displayName() throws Exception // get all the name
{
String name = null;
String sql="Select name from admin";
DatabaseConnection db = new DatabaseConnection();
Connection conn =db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
name= rs.getString("name");
}
ps.close();
rs.close();
conn.close();
return name ;
}
You currently return a single String, and your method iterates all of the admin names (but terminates after the final row, so that's your result). Instead, build a List of names and return that. You could also use a try-with-resources close to close your Connection, Statement and ResultSet instances. Something like
public List<String> displayName() throws Exception // get all the name
{
String sql = "Select name from admin";
List<String> names = new ArrayList<>();
DatabaseConnection db = new DatabaseConnection();
try (Connection conn = db.getConnection();
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
names.add(rs.getString("name"));
}
}
return names;
}
This might be helpful
private String names[];
int i = 0;
while (rs.next()) {
names[i] = rs.getString("name");
i++;
}
Then you can use a for loop to return each name in StaffManagement.java
I want message (the row is not available in the stock) if row is not available in the database. I try the following code but the error....!
//Code
try {
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
int count = 0;
while (rs.next()){
count = count + 1;
}
if (count == 1) {
JOptionPane.showMessageDialog(null, "Item is available in Stock"
} else {
JOptionPane.showMessageDialog(null, "ID:" + txtS.getText() + "is not available in the Stock please update the Stock");
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
e.printStackTrace();
}
// error....
java.sql.SQLException: No value specified for parameter 1
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:896)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:885)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:860)
.....
.....
....
....
Please help.....
You are not setting the value for the ? in your SELECT statement.
Given that it's an ID I will assume it is an int.
You need:
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, value);
ResultSet rs = ps.executeQuery();
EDIT
Try changing your methodology to this:
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setInt(1, value);
ResultSet rs = ps.executeQuery();
if(rs.next()){
JOptionPane.showMessageDialog(null, "Item is available in Stock"
}
else {
JOptionPane.showMessageDialog(null, "ID:" + txtS.getText() + "is not available in the Stock please update the Stock");
}
Thanks # Matt for help
i got a perfect Answer by using this code......
try {
Connection con = Database.mySqlCon();
String sql = "SELECT count(*) FROM stock WHERE idProduct =?";
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, txtS.getText());
ResultSet rs = ps.executeQuery();
int count = 0;
while (rs.next()){
// code update here
count = rs.getInt(1);
// count = count + 1;
}
if (count == 1) {
Every time I run this code it gives me an exhauset resultset error. Im not sure what Im doing wrong but Ive tried removing the .next(); code for either one or all resultsets and then the error given is the ResultSet next wasnt called.
Im not sure what Im doing wrong. Just curious what people might think the issue could be? Ive done similar earlier in my servlet code but only used 1 statement and then 1 prepared statement. This time Im using 2 statements and 1 prepared statement.
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
rs11.next();
ResultSet rs12 = stmt.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
rs12.next();
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
int olo1 = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)");
pstmt1.clearParameters();
pstmt1.setInt(1,olo);
pstmt1.setInt(2,olo1);
ResultSet rs1 = pstmt1.executeQuery();
rs1.next();
Some ideas on your code (in comments)
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
//Check if you HAVE a line here!
if(!rs11.next()) {
System.out.println("No Recipe Found");
}
//Use stmt1 - that's why you created it?!
ResultSet rs12 = stmt1.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
if(!rs12.next()) {
System.out.println("No Ingredient Found");
}
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
//Read Ingredient from rs12 -> that's where you selected it into
int olo1 = ((Number) rs12.getObject(1).intValue(); //convert resultset value to int
While this might point you into the right direction for solving the current issue, you should consider learning about clean code.
Consider this code making use of try-with-resource, refactored out some methods, using prepared statements.
//Replace exiting code
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
int recipieId = getRecipeId(con, opt1);
int ingredientId = getIngredientId(con, ingr1);
if(recipeId > 0 && ingredientId > 0) {
//Process result
insertRecLnk(con, recipeId, ingredientId);
} else {
System.out.println("No INSERT");
}
//Helper functions
protected int getRecipeId(Connection con, String rec) {
try(PreparedStatement st = con.prepareStatement("SELECT recipe_ID FROM GM_Recipes WHERE rec_name=?")) {
st.setString(1, rec);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Recipe Found");
return -1;
}
protected int getIngredientId(Connection con, String ing) {
try(PreparedStatement st = con.prepareStatement("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name=?")) {
st.setString(1, ing);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Ingredient Found");
return -1;
}
protected void insertRecLnk(Connection con, int rId, int iId) {
try(PreparedStatement ps = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)")) {
ps.setInt(1, rId);
ps.setInt(2, iId);
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
}
I am trying to update a table in the database where i m accepting fees from the students and maintaining the record of the amount received, total amount received, and the mode of payment etc.
my code is as follows:
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl,"root","17121990");
System.out.println("connected!");
String firstname=pay_enter_firstname.getText();
String lastname=pay_enter_lastname.getText();
String amt=pay_enter_amt.getText();
int amount=Integer.parseInt(amt);
String day=pay_enter_date.getText();
String cheque_no=pay_enter_chequeno.getText();
String mode=pay_enter_mode.getText();
int totalamount=10000;
int bal_amt=totalamount-amount;
String remark=pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
if(rs.next())
{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
while(rs.next())
{
int temp =rs.getInt(1);
if (temp ==id)
{
int amtrecvd2= rs.getInt(2);
bal_amt=totalamount- (amtrecvd2+amount);
String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
}
}
}
if(!rs.next())
{
String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
Statement stmt1=con.createStatement();
int result=stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
}
catch (ClassNotFoundException | SQLException | NumberFormatException e)
{
e.printStackTrace();
}
}
Initially when i add new values i get it properly but when i am trying to update an existing row i get the error that i m making a duplicate entry for primary key id.
what condition should i check so that i come to know that the result set is not having that particular id value and new person is paying the fee??
This condition:
if(!rs.next())
is being checked outside the while loop. This condition is always true and will try to insert a record even if update has taken place.
To avoid this, i suggest using a flag variable. Once an update has occurred, set the value of this flag to 1.
Check if it has been made 1 instead of if(!rs.next()) and go inside.
You're two if statements are colliding...
// If this is true...
if(rs.next()) {
// ...
// Looping till the it's false...
while(rs.next()) {
// ....
}
}
// Will mean that this is false...
if(!rs.next())
You should be using an else
if(rs.next()) {
// ...
while(rs.next()) {
// ....
}
} else {...}
Updated
After an enlightening conversion with Aashray (thanks), we've concluded that your logic is broken
Rather then manually trying to find the record manually by match the id's let the SQL database do it for you.
Instead of....
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
You should be using...
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);
This will return a ResultSet that is either empty (no matches) or with (hopefully) one row.
From there, calling rs.next() will now let you branch of between an update or insert correctly.
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, "root", "17121990");
System.out.println("connected!");
String firstname = pay_enter_firstname.getText();
String lastname = pay_enter_lastname.getText();
String amt = pay_enter_amt.getText();
int amount = Integer.parseInt(amt);
String day = pay_enter_date.getText();
String cheque_no = pay_enter_chequeno.getText();
String mode = pay_enter_mode.getText();
int totalamount = 10000;
int bal_amt = totalamount - amount;
String remark = pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment where id = " + id);
if (rs.next()) {
int amtrecvd2 = rs.getInt(2);
bal_amt = totalamount - (amtrecvd2 + amount);
String updt = "UPDATE payment SET Amountreceivd=" + (amtrecvd2 + amount) + ",lastamtreceived=" + amount + ",dte='" + day + "', balance_amt =" + bal_amt + " WHERE id =" + id + ";";
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
} else {
String str = " INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES (" + id + ",'" + firstname + "','" + lastname + "'," + amount + ",'" + day + "'," + amount + ",'" + mode + "','" + cheque_no + "'," + bal_amt + "," + totalamount + ",'" + remark + "')";
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
} catch (ClassNotFoundException | SQLException | NumberFormatException e) {
e.printStackTrace();
}
}
I think this may help you
private void pay_saveActionPerformed(java.awt.event.ActionEvent evt) {
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
PreparedStatement ps1 = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection (dbUrl,"root","17121990");
System.out.println("connected!");
String firstname=pay_enter_firstname.getText();
String lastname=pay_enter_lastname.getText();
String amt=pay_enter_amt.getText();
int amount=Integer.parseInt(amt);
String day=pay_enter_date.getText();
String cheque_no=pay_enter_chequeno.getText();
String mode=pay_enter_mode.getText();
int totalamount=10000;
int bal_amt=totalamount-amount;
String remark=pay_enter_remark.getText();
int id = Integer.parseInt(pay_enter_id.getText());
Statement stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
if(rs.next())
{
stmt = con.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
rs = stmt.executeQuery("SELECT id, lastamtreceived FROM payment");
while(rs.next())
{
int temp =rs.getInt(1);
if (temp ==id)
{
int amtrecvd2= rs.getInt(2);
bal_amt=totalamount- (amtrecvd2+amount);
String updt = "UPDATE payment SET Amountreceivd="+(amtrecvd2+amount)+",lastamtreceived="+amount+",dte='"+day+"', balance_amt ="+bal_amt+" WHERE id ="+temp+";" ;
Statement stmt1 = con.createStatement();
int result = stmt1.executeUpdate(updt);
}
}
}
else
{
String str=" INSERT INTO payment(id, firstname,lastname,Amountreceivd,dte,lastamtreceived,Creditcashcheque,"
+ "cheque_no,balance_amt,totalamount,Remark) VALUES ("+id+",'"+firstname+"','"+lastname+"',"+amount+",'"+day+"',"+amount+",'"+mode+"','"+cheque_no+"',"+ bal_amt+","+totalamount+",'"+remark+"')";
Statement stmt1=con.createStatement();
int result=stmt1.executeUpdate(str);
panel_feesframe.setVisible(false);
}
panel_feesframe.setVisible(false);
con.close();
}
catch (ClassNotFoundException | SQLException | NumberFormatException e)
{
e.printStackTrace();
}