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

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

Related

try-with-resources JDBC with multiple resources and an else statement

This is a method to add a new planet to an observablelist of customers.
I am wondering if I am using the try with resources correctly and if the auto-close is working.
public static Customer addPlanet(Customer customer) {
String query1 = "Select * from planet where planet=? AND universeID=?";
String query2 = "INSERT INTO planet (planet,universeID) VALUES(?,?)";
try (PreparedStatement statement = (PreparedStatement) Database.connection.prepareStatement(query1);
PreparedStatement statement2 = (PreparedStatement) Database.connection.prepareStatement(query2)) {
statement.setString(1, customer.getPlanet());
statement.setString(2, Integer.toString(customer.getUniverseID()));
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
int planetId = rs.getInt(1);
customer.setPlanetID(planetId);
return customer;
} else {
statement2.setString(1, customer.getPlanet());
statement2.setInt(2, customer.getUniverseID());
statement2.executeUpdate();
return addPlanet(customer);
}
} catch (SQLException e) {
e.printStackTrace();
return null;
}
} catch (SQLException e) {
e.printStackTrace();
}
return customer;
}
My question is, does this part need to be enclosed in a try-catch block or does it get closed automatically.
statement2.executeUpdate();
It gets closed. Anything in the try gets closed at the end if they are AutoCloseable.

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

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

Null result statement from other class

The result set that I'm trying to retrieve from another class returns null, even though the query works.I'm trying to initialize my object based on the records kept in databases,which means if there is initially a record in sqlite,I retrieve the one with latest date.Else,I try to retrieve the earliest one from mysql database. The code that is supposed to retrieve result set from mysql database is like this:
public ResultSet lowestDate() throws SQLException {
ResultSet rs1 = null;
String resultQuery = "SELECT * FROM alarm ORDER BY `timestamp` ASC LIMIT 1";
rs1 = stmt.executeQuery(resultQuery);
return rs1;
}
Statement is initialized globally.And I call this in another class like this:
public void setLastAlarm() throws SQLException, ParseException {
String liteQuery = "SELECT * FROM alarm_entries ORDER BY date(`timestamp`) DESC LIMIT 1";
conn.connectLite();
Connection getCon = conn.getLiteConnection();
try {
stmt = getCon.createStatement();
} catch (SQLException e) {
e.printStackTrace();
}
try {
rs = stmt.executeQuery(liteQuery);
if (rs.next()) {
//while (rs.next()) {
nuDate = rs.getString("timestamp");
newDate = format.parse(nuDate);
lastAlarm.setBacklogId(rs.getBytes("backlog_id"));
lastAlarm.setTimestamp(newDate);
//}
}
else{
rsq=mysqlConnection.lowestDate();
lastAlarm.setTimestamp(format.parse(rsq.getString("timestamp")));
lastAlarm.setBacklogId(rsq.getBytes("backlog_id"));
}
}catch (Exception e){
e.printStackTrace();
}
}
public void run() {
try {
setLastAlarm();
You never call ResultSet#next() on the result set being returned from the lowestDate() helper method. Hence, the cursor is never being advanced to the first (and only) record in the result set. But I think it is a bad idea to factor your JDBC code in this way. Instead, just inline your two queries like this:
try {
rs = stmt.executeQuery(liteQuery);
if (rs.next()) {
nuDate = rs.getString("timestamp");
newDate = format.parse(nuDate);
lastAlarm.setBacklogId(rs.getBytes("backlog_id"));
lastAlarm.setTimestamp(newDate);
}
else {
String resultQuery = "SELECT * FROM alarm ORDER BY timestamp LIMIT 1";
rs = stmt.executeQuery(resultQuery);
if (rs.next()) {
String ts = rs.getString("timestamp");
lastAlarm.setTimestamp(format.parse(ts));
lastAlarm.setBacklogId(rs.getBytes("backlog_id"));
}
}
} catch (Exception e){
e.printStackTrace();
}

Login doesn't work even if data is present in SQLite database [duplicate]

This question already has answers here:
Multiple returns: Which one sets the final return value?
(7 answers)
Closed 5 years ago.
I have a database and it has a table user which consists of many attributes like name ,email,etc. Also it has username and password in VARCHAR datatype. I wrote two classes LoginModel and Controller. controller has method loginit through which it checks if login method from LoginModel returns true or not. I am not able to find out why LoginModel always returns false. Please help.
Here are my methods :
from class LoginModel
public boolean login(String userid, String userpass) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM user WHERE username = ? AND password = ?";
try{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,userid);
preparedStatement.setString(2,userpass);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return true;
}
else {
// System.out.println(resultSet.next());
return false;
}
}
catch (Exception e){
return false;
}
finally {
preparedStatement.close();
resultSet.close();
return false;
}
}
from class Controller
public void loginit() throws SQLException {
String userid = uid.getText();
String userpass = upass.getText();
try {
if (loginmodel.login(userid, userpass)) {
lblstatus.setText("YES");
}
else
lblstatus.setText("Invalid");
} catch (SQLException e) {
lblstatus.setText("No");
e.printStackTrace();
}
}
It is a JavaFX application. userid and userpass are ids of text-field and password-field respectively. lblstatus is label which always shows Invalid, can't figure out why!
Here is snapshot of my database
remove return false from the finally block. It will executed in case of execption and in case you get no exception.
finally {
preparedStatement.close();
resultSet.close();
return false;
}
Change your code to:
public boolean login(String userid, String userpass) throws SQLException {
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
String query = "SELECT * FROM user WHERE username = ? AND password = ?";
try{
preparedStatement = connection.prepareStatement(query);
preparedStatement.setString(1,userid);
preparedStatement.setString(2,userpass);
resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
return true;
}
else {
// System.out.println(resultSet.next());
return false;
}
}
catch (Exception e){
return false;
}
finally {
preparedStatement.close();
resultSet.close();
}
return false;
}

Findbugs error "Load of known null value" SQL connection

I have DAO class with methods getting and sending data.
I'm catching Exceptions inside SQL requests, so I need to declare connection variables outside of try parenthesis.
every method looks lookes like this:
public Role getRole(int roleId) {
Connection connection = null;
ResultSet rs = null;
PreparedStatement statement = null;
Role role = null;
try {
connection = dataSource.getConnection();
statement = connection.prepareStatement("select ROLE_ID, ROLE_TEXT from ROLES WHERE ROLE_ID = :1");
statement.setInt(1, roleId);
rs = statement.executeQuery();
rs.next();
role = roleMapper.mapRow(rs, 1);
} catch (SQLException e) {
} finally {
JdbcUtils.closeResultSet(rs);
JdbcUtils.closeStatement(statement);
JdbcUtils.closeConnection(connection);
return role;
}
}
But there's problem. Finbugs giving me an error, saying:
Load of known null value in DAO.getRole
and
may fail to clean up java.sql.Statement
So what should I do to avoid that?
The getRole can return null.
Furthermore:
if (rs.next()) {
role = roleMapper.mapRow(rs, 1);
}
I prefer another notation. And the error solution unfortunately consists of either letting getRole throw an exception (best) or letting return an Optional<Role>
//public Role getRole(int roleId) throws SQLException {
public Optional<Role> getRole(int roleId) {
try (Connection connection = dataSource.getConnection();
PreparedStatement statement =
connection.prepareStatement(
"select ROLE_ID, ROLE_TEXT from ROLES WHERE ROLE_ID = :1")) {
statement.setInt(1, roleId);
try (ResultSet rs = statement.executeQuery()) {
if (rs.next()) {
return roleMapper.mapRow(rs, 1);
}
}
} catch (SQLException e) { //
Logger.getLogger(getClass().getName()).log(Level.SEVERE, "ID: " + roleId, e); //
}
return Optional.empty(); //
}

Categories