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);
}
}
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
I have this code for searching in the MySQL data table by id, but when I run the program it is giving me this error (Output : "Column 'Mart' Not Found"). I'm using JTextFiled to ask the user to enter the id that want to search for.
public void actionPerformed(ActionEvent event) {
if(event.getSource()== btn) {
try {
Connection connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement st = connection.prepareStatement("Select ID,user_name_1,password FROM Admin Where ID = ?");
int id = Integer.parseInt(text.getText());
st.setInt(1, id);
ResultSet rs = st.executeQuery();
if(rs.next()==false) {
JOptionPane.showMessageDialog(null, "The ID Not Found!!");
}
else {
String user = rs.getString("user_name_1");
text2.setText(rs.getString(user));
String pass = rs.getString("password");
text3.setText(rs.getString(pass));
}
}
catch (Exception e) {
System.out.print(e.getMessage());
}
}
}
Check if your column names are the same as the ones in the Database
Check if your connection string is connecting to the correct database
Ensure Database Driver is added
Try this:
public class DatabaseClass {
private String url = "YOUR URL";
private String username = "YOUR USERNAME";
private String password = "YOUR PASSWORD";
private static DatabaseClass theDB = new DatabaseClass();
private Connection c;
private DatabaseClass() {
try {
Class.forName("com.mysql.jdbc.Driver");
c = DriverManager.getConnection(url, username, password);
} catch (Exception ex) {
System.out.println("Error Connection: " + ex);
}
}
public Connection getC() {
return this.c;
}
public static DatabaseClass getInstance() {
return theDB;
}
}
And then, the click event:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try {
HashMap<Integer, String> data = new HashMap<>();
int id = Integer.parseInt(jTextField1.getText());
Connection c = DatabaseClass.getInstance().getC();
PreparedStatement s = c.prepareStatement("select * from yourTable where ID = ?");
s.setInt(1, id);
ResultSet theResult = s.executeQuery();
while (theResult.next()) {
int yourID = theResult.getInt("ID");
String yourData = theResult.getString("Email_Address");
data.put(yourID, yourData);
}
for (HashMap.Entry theEntry : data.entrySet()) {
jTextArea1.append(String.valueOf(theEntry.getKey()) + " " + theEntry.getValue() + "\n");
}
} catch (Exception ex) {
System.out.println("Error: " + ex);
}
}
Ideally this should work, but replace the query with your query and the connection string with yours.
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
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 = ?";
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
ValidateLogin.java
public boolean testLogin(LoginHandler user)
{
String query = null;
try
{
stmt = connect.createStatement();
query = "SELECT * FROM users WHERE UserName = '"+user.getUsername()+"'";
rs = stmt.executeQuery(query);
rs.next();
if(rs.getString(2).equals(user.getUsername()) && rs.getString(3).equals(user.getPassword()))
{
this.closeDB();
return true;
}
else
{
JOptionPane.showMessageDialog(null,"Login Failed: Invalid Password");
}
}
catch(SQLException ex)
{
JOptionPane.showMessageDialog(null,"Login Failed: Invalid Username");
}
this.closeDB();
return false;
}
LoginHandler.java
public boolean verifyUser()
{
if(super.testLogin(this))
{
mainWindow mainwindow = new mainWindow();
mainwindow.setVisible(true);
return true;
}
return false;
}
i already saved username and password fields in my database..
how can i retrieve them in my loginWindow???
everytime i enter the username and password.. the message it displays is : "Login Failed: Invalid Password"
anyone help please??
try this
PreparedStatement ps = connect.prepareStatement("SELECT * FROM users WHERE UserName =?");
ps.setString(1,user.getUsername());
rs = ps.executeQuery();
use column name instead of index value
uname & pass are variable
while (rs.next()) {
uname=rs.getString("UserName");
pass=rs.getString("Password");
}
if(uname.equals(user.getUsername()) && pass.equals(user.getPassword()))
{
this.closeDB();
return true;
}