java.sql.SQLException: Column 'Max(category_id' not found - java

Here is my code. It gives me an exception error says "java.sql.SQLException: Column 'Max(category_id' not found.". Please help. Thanks in advance.
enter code here
public class Category extends javax.swing.JFrame {
/**
* Creates new form Category
*/
public Category() {
initComponents();
DisplayTable();
autoID();
}
//Display Table
private void DisplayTable() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
String sql = "SELECT * FROM category";
PreparedStatement pstmt = conn.prepareStatement(sql);
ResultSet rs = pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
public void autoID() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory?useTimezone=true&serverTimezone=UTC", "root", "ichigo197328");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT Max(category_id) from category");
rs.next();
rs.getString("Max(category_id)");
if(rs.getString("Max(category_id") == null) {
CategoryIDField.setText("C0001");
}
else {
Long id = Long.parseLong(rs.getString("Max(category_id").substring(2, rs.getString("Max(category_id").length()));
id++;
CategoryIDField.setText("C0" + String.format("%03d", id ));
}
}
catch(ClassNotFoundException e) {
Logger.getLogger(Category.class.getName()).log(Level.SEVERE, null, e);
}
catch(SQLException e) {
Logger.getLogger(Category.class.getName()).log(Level.SEVERE, null, e);
}
}

The column has a default name but it isn't the same as the function, the easiest option would be to change all
rs.getString("Max(category_id)");
to
rs.getString(1);
Alternatively, name the column in your query. Like,
ResultSet rs = s.executeQuery("SELECT Max(category_id) AS FRED from category");
then use
rs.getString("FRED");
for example. Finally, you should be using getInt or getLong if the column is of those types (which I suspect because you are taking the MAX).

I think in the line
if(rs.getString("Max(category_id") == null) {
CategoryIDField.setText("C0001")
the quote should be after the round bracket.

use alisa
select Max(category_id) as xxx from category

Related

How to search a database to verify it exists?

I have been working with a java database for this class I'm just trying to search and see if the entry with the same name the user inputs exists. It used to work but for some, it keeps saying it doesn't exist in the database even if it does. If someone could give me a solution it would be greatly appreciated.
private void btnSearchActionPerformed(java.awt.event.ActionEvent evt) {
name = txtSearch.getText();
sr.setSearch(name);
try {
String url = "jdbc:derby://localhost:1527/Cookbook";
Connection conn = DriverManager.getConnection(url);
String sql = "SELECT * from RECIPES where NAME = ?";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, name);
ResultSet rs = pst.executeQuery();
boolean found = false;
while (rs.next()) {
if (rs.getString(1).equalsIgnoreCase(name)) {
JOptionPane.showMessageDialog(null, "Found " + name);
found = true;
break;
}
}
if (found) {
this.dispose();
modifyingRecipe m = new modifyingRecipe();
m.setVisible(true);
} else {
JOptionPane.showMessageDialog(null, "Item Not Found!");
}
} catch (SQLException ex) {
Logger.getLogger(CookbookApp.class.getName()).log(Level.SEVERE, null, ex);
}
}

Using two combobox to set conditions for a search in a database and displaying in jtable

I need to display the details of students in a particular stream of a schoolclass in Jtable from a database containing all the names of students in the school. I have two jComboboxes, on to select which class and the other to select the stream. I am asking for a way to define these two conditions in order to display all the students in a particular stream in a jtable. I apologize in advance if my code is messy.
public Classes() {
initComponents();
show_student();
}
public Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sms", "root", "");
} catch(Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
return con;
}
public ArrayList<Individualclass> studentList(String ValToSearch) {
ArrayList<Individualclass> list = new
ArrayList<Individualclass>();
Statement st;
ResultSet rs;
try {
Connection con=getConnection();
st = con.createStatement();
String searchQuery = "SELECT * FROM `students` WHERE CONCAT(`firstName`, `surname`, `otherNames`, `regNo`) LIKE '%"+ValToSearch+"%'";
rs = st.executeQuery("searchQuery ");
Individualclass ic;
while(rs.next()) {
ic = new Individualclass(
rs.getString("firstName"),
rs.getString("surname"),
rs.getString("otherNames"),
rs.getInt("regNo")
);
list.add(ic);
}
} catch(Exception ex){
JOptionPane.showMessageDialog(null, ex.getMessage());
}
return list;
}
public void findStudents() {
}
private void sClassActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_sClassActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where sClass=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String) sClass.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_sClassActionPerformed
private void streamActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_streamActionPerformed
try {
Connection con = getConnection();
String fetch_row = "SELECT * FROM students where stream=?";
PreparedStatement pst = con.prepareStatement(fetch_row);
pst.setString(1, (String)stream.getSelectedItem());
ResultSet rs = pst.executeQuery();
while(rs.next()) {
Individualclass ic = new Individualclass(rs.getString("firstName"),rs.getString("surname"),rs.getString("otherNames"),rs.getInt("regNo"));
}
} catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex.getMessage());
}
}//GEN-LAST:event_streamActionPerformed
public void show_student() {
ArrayList<Individualclass> list = new ArrayList<Individualclass>();
DefaultTableModel model = (DefaultTableModel)jTable_Display_Student.getModel();
Object [] row = new Object[13];
for(int i = 0; i < list.size(); i++) {
row[0] = list.get(i).getFirstName();
row[1] = list.get(i).getsurname();
row[2] = list.get(i).getOtherNames();
row[3] = list.get(i).getregNo();
model.addRow(row);
}
}

java.sql.SQLExecption:parameter index out of range (1>number of prameters, which is 0) for update sql

i have problem with my project, and it still new for me with MYSQL, i want to get data from database and do some calculation and update the value on it,
its like making withdraw function like ATM machine. This my table look like.
enter image description here . You can see constructor parameter that carry value (String value and String ID). For Value="100"; and ID="5221311" you can see it on my table picture.
public ConformWithdraw() {
initComponents();
try {
Class.forName("com.jdbc.mysql.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:/atm", "root", "");
} catch (Exception e) {
System.out.println(e.getMessage());
}
}
public ConformWithdraw(String value,String ID) {
initComponents();
this.value=value;
this.ID=ID;
}
------------------------------------------------------------
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
String validate = "SELECT * FROM customer_details WHERE accountID LIKE '" + ID
+ "'";
PreparedStatement smtm = con.prepareStatement(validate);
ResultSet resultSet = smtm.executeQuery();
User user = null;
if (resultSet.next()) {
user = new User();
user.setBalance(resultSet.getString("accountBalance"));
double balance=Double.parseDouble(user.getBalance());
double val=Double.parseDouble(value);
total =(balance - val);
}
smtm.close();
resultSet.close();
program();
} catch (SQLException | HeadlessException | ClassCastException ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
-------------------------------------------------------------
public void program(){
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = '"+String.valueOf(total)+"'"
+ "WHERE accountID = '"+ID+"'";
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/atm?zeroDateTimeBehavior=convertToNull", "root", "");
PreparedStatement pstmt = con.prepareStatement(sqlUpdate);
id=Integer.parseInt(ID);
pstmt.setString(1, String.valueOf(total));
pstmt.setInt(2, id);
int rowAffected = pstmt.executeUpdate();
pstmt.close();
new ShowWithdraw().setVisible(true);
dispose();
}catch(SQLException | HeadlessException | ClassCastException ex){
JOptionPane.showMessageDialog(null, ex);
JOptionPane.showMessageDialog(null, "slh sini");
}
}
You are already setting the parameters on the query, so It tries to set the parameters and find no parameters to find. Try this:
String sqlUpdate = "UPDATE customer_details "
+ "SET accountBalance = ?"
+ "WHERE accountID = ?";

radio button show values in combo box

I confused with this if-else because I'm new in Java & MySQL and I tried to make it by myself.
public Menu() {
initComponents();
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/restaurant", "root", "");
System.out.println("ODBC Connection Successful");
showCategory();
} catch (ClassNotFoundException | SQLException e) {
System.out.println("ODBC Connection Failed" + e);
}
}
if - else
private void showCategory() {
try {
Statement stmt;
stmt = con.createStatement();
if (rbMFood.isSelected()) {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY02'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
} else {
ResultSet rs = stmt.executeQuery("SELECT * FROM menu_cat WHERE type_id = 'TY01'");
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Radio Button
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Food";
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
type = "Drink";
}
And I declare the function in the end of the program
private String type;
When I click drink / food, the category still drink's category.
The database
Any help would be greatly appreciated!
You are using rs.getString("menu_cat") But the format is rs.getString(<Column Name>) But you are using rs.getString(<Table Name>) As "menu_cat" is name of the table and not the name of the column.
AFTER POSTING CONSTRUCTOR
What I see from the code you have posted, is that You have called showCategory() in the constructor. This method is responsible for populating the JComboBox cmbMCat. Now the cmbMCat is being populated when you are creating the new Menu. After that the items list of the cmbMCat does not change.
So, What I suggest is that you call the showCategory() from the rbMFoodActionPerformed and rbMDrinkActionPerformed methods. I hope this will solve your problem.
Also add cmbMCat.removeAllItems() before Statement stmt; to remove all the items that are there in the cmbMCat and reset it with a fresh list of items.
After comment regarding the if-else
Change the showCatagory() as below:
private void showCategory() {
cmbMCat.removeAllItems();
try {
PreparedStatement stmt; //Used Prepared statement
String sql = "SELECT * FROM menu_cat WHERE type_id = ?";
stmt = con.prepareStatement(sql);
if (type.equals("Drink")) {
stmt.setString("TY01");
} else {
stmt.setString("TY02");
}
ResultSet rs = stmt.executeQuery();
while (rs.next()) {
cmbMCat.addItem(rs.getString("menu_cat"));
}
}
} catch (Exception e) {
}
}
Also note that you eventListener code should be:
private void rbMFoodActionPerformed(java.awt.event.ActionEvent evt){
type = "Food";
showCategory();
}
private void rbMDrinkActionPerformed(java.awt.event.ActionEvent evt){
type = "Drink";
showCategory();
}

Getting a true(1) or false(0) from specific sql statement

I need help with the code below and getting it to return a true or false value. Any and all help would be appreciated.
public synchronized static boolean checkCompanyName(String companyName,
Statement statement) {
try {
ResultSet res = statement
.executeQuery("SELECT `companyName` FROM `companys` WHERE companyName = '"
+ companyName + "';");
boolean containsCompany = res.next();
res.close();
return containsCompany;
} catch (Exception e) {
e.printStackTrace();
return false;
}
}
Try to make your query like this:
ResultSet res = statement.executeQuery("SELECT companyName FROM companys WHERE companyName = " + companyName);
Or you can either you PreparedStatement which is better then you did before
You should be using a PreparedStatement (for that end pass the Connection in to the method). Also, you should retrieve the value from the ResultSet and validate it matches your companyName. Something like
static final String query = "SELECT `companyName` FROM "
+ "`companys` WHERE companyName = ?";
public synchronized static boolean checkCompanyName(String companyName,
Connection conn) {
PreparedStatement ps = null;
ResultSet rs = null;
try {
ps = conn.prepareStatement(query);
ps.setString(1, companyName);
rs = ps.executeQuery();
if (rs.next()) {
String v = rs.getString(1);
return v.equals(companyName);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
}
}
}
return false;
}
Two comments:
You only need to check if there's at least one row matching your criteria, so you can use .first()
Your code is vulnerable to SQL Injection attacks. Please read this to learn more about it.
The easiest way to avoid SQL injection attacs is to use prepared statements. So let me strike two birds with a single stone and give you a solution using them:
/*
Check if the company exists.
Parameters:
conn - The connection to your database
company - The name of the company
Returns:
true if the company exists, false otherwise
*/
public static boolean checkCompanyName(Connection conn, String company) {
boolean ans = false;
try(PreparedStatement ps = conn.prepareStatement(
"select companyName from companies where companyName = ?"
) // The question mark is a place holder
) {
ps.setString(1, company); // You set the value for each place holder
// using setXXX() methods
try(ResultSet rs = ps.executeQuery()) {
ans = rs.first();
} catch(SQLException e) {
// Handle the exception here
}
} catch(SQLException e) {
// Handle the exception here
}
return ans;
}
Suggested reads:
Bobby Tables: A guide to preventing SQL injection
The Java Tutorials - JDBC: Using prepared statements

Categories