NullPointerException when using executeQuery - java

I have a null pointer exception in
ResultSet rs = aStatement.executeQuery(Query); // it can't be executed
my code is like this :
public static boolean testLogin(String user, String password) throws SQLException {
String Query = "select * from TBL_Users where userName = '" + user + "' and passWord = '" + password + "' ";
ResultSet rs = aStatement.executeQuery(Query);
while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true;
}
return false;
}
}

Most likely aStatement is null.

Sounds like you think aStatement should not be null, but it is.
This is bad JDBC code, for many reasons:
No cleanup of resources.
Doesn't use PreparedStatement
Keeps creating the query string over and over again instead of using a static variable
Doesn't follow Java coding standards ("Query" should be "query")
Here's another way to write it. Start with an interface:
package persistence;
import java.sql.SQLException;
public interface CredentialDao
{
boolean isValidUser(String username, String password) throws SQLException;
}
Write an implementation:
package persistence;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class CredentialDaoImpl implements CredentialDao
{
private static final String CREDENTIAL_QUERY = "SELECT COUNT() FROM USER WHERE USERNAME = ? AND PASSWORD = ?";
private Connection connection;
public CredentialDaoImpl(Connection connection)
{
this.connection = connection;
}
public boolean isValidUser(String username, String password) throws SQLException
{
boolean isValidUser = false;
PreparedStatement ps = null;
ResultSet rs = null;
try
{
ps = this.connection.prepareStatement(CREDENTIAL_QUERY);
ps.setString(1, username);
ps.setString(2, password);
rs = ps.executeQuery();
while (rs.next())
{
int count = rs.getInt(1);
isValidUser = (count > 0);
}
}
finally
{
DatabaseUtils.close(rs);
DatabaseUtils.close(ps);
}
return isValidUser;
}
}

The aStatement variable is apparently null, please validate that it is correctly set. You should consider read the Java Naming Conventions and make sure you use the lower camel case for variables and java bean conventions.
For code snippets in stackoverflow if they are not self-explanatory, you should obey the rules of the SSCCE, this will help you to get more and better answers. Also you should provide a stack trace with the occured exception.

Use prepared statements.
Connection con = ...; // obtain connection here
PreparedStatement pstmt = con.prepareStatement("select * from TBL_Users where userName = ?'");
pstmt.setInt(1, userName);
ResultSet rs = pstmt .executeQuery();
...
// do clean up here

while (rs.next()) {
info.Id = rs.getInt("ID");
info.userName = rs.getString("userName");
info.Name = rs.getString("User_Name");
info.Password = rs.getString("passWord");
info.isAdmin = rs.getBoolean("Admin");
return true; // Huh? What?
}
What is info refering to and why is there a return imediatly after the assignments?

Related

How to use a variable value declared in servlet into a new Java class?

I have a login servlet where I have a login query in my post method from the query I am getting username, password, company name and ID
I am storing all this values in a variable like
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String companyDB,nameDB,idDB;
try {
con = DBConnection.createConnection();
statement = con.createStatement();
String sql = " SELECT MT_USERS.MT_USERS_VCLOGINCODE AS USERID, MT_USERS.MT_USERS_VCUSERPASSWORD AS PASSWORDID, MT_USERS.MT_USERS_VCUSERNAME AS NAME, (SELECT MT_DISTRIBUTR_VCDISTRIBUTRNAME FROM MT_DISTRIBUTR WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS COMPANYNAME ,(SELECT mt_distributr_vcdistributrcode FROM mt_distributr WHERE MT_DISTRIBUTR_VCDISTRIBUTRCODE = MT_USERS.MT_DISTRIBUTR_VCDISTRIBUTRCODE) AS ID FROM MT_USERS WHERE MT_USERS_VCLOGINCODE='admin' AND MT_USERS_VCUSERPASSWORD ='admin'";
resultSet = statement.executeQuery(sql);
if (resultSet.next()) {
companyDB = resultSet.getString("COMPANYNAME");
nameDB = resultSet.getString("name");
idDB = resultset.getString("ID");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
Now I have an another class where I am writing a query and in that query I want to use idDB like
My new class is
public class Outlet {
Connection con = null;
Statement statement = null;
ResultSet resultSet = null;
public List<String> getoutlet() throws ClassNotFoundException, SQLException {
List<String> list = new ArrayList<String>();
con = DBConnection.createConnection();
statement = con.createStatement();
try {
ResultSet resultSet = statement.executeQuery("select * from ecustomer where CUSTOMERIDENTIFIER in(select CUSTOMERIDENTIFIER from mt_distributrol where mt_distributr_vcdistributrcode = 'AAAA'");
while (resultSet.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
}
Where mt_distributr_vcdistributrcode = 'AAAA'" at the place of 'AAAA' I have to pass a variable which has the value of idDB
You may use a prepared statement here:
String sql = "SELECT CUSTOMERDESCRIPTOR FROM ecustomer WHERE CUSTOMERIDENTIFIER IN (";
sql += "SELECT CUSTOMERIDENTIFIER FROM mt_distributrol ";
sql += "WHERE mt_distributr_vcdistributrcode = ?)");
PreparedStatement ps = con.prepareStatement(sql);
ps.setString(1, "AAAA");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
list.add(resultSet.getString("CUSTOMERDESCRIPTOR"));
}
I actually find that MkYong does a good job of explaining prepared statements in Java, see here, but any good documentation is a good place to start looking. And see Oracle Tutorial.

Field can be converted to local variable

I have this error: Field can be converted to local variable.
for preparedStatement
package game;
import java.sql.*;
public class db {
private Connection connection;
private PreparedStatement preparedStatement;
public db() throws SQLException,ClassNotFoundException {
Class.forName("com.mysql.cj.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/riverraider";
String user = "root";
String pass = "146155";
connection = DriverManager.getConnection(url,user,pass);
}
public String select(String username, String password) throws Exception
{
preparedStatement = connection.prepareStatement("SELECT * FROM `user` WHERE `username`=? AND `password`=? ");
preparedStatement.setLong(1, Long.parseLong(username));
preparedStatement.setLong(1, Long.parseLong(password));
ResultSet result = preparedStatement.executeQuery();
while (result.next()!=false){
System.out.println("Username or password is incorrect.");
}
}
}
Most likely, the error/warning is just stemming from your declaring the variable preparedStatement as a class level variable, when it can just be a variable local to the select() method with the same effect. Try removing that declaration from the class level, and instead using this version of select():
public String select(String username, String password) throws Exception {
String sql = "SELECT * FROM user WHERE username = ? AND password = ?";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setLong(1, Long.parseLong(username));
ps.setLong(1, Long.parseLong(password));
ResultSet result = ps.executeQuery();
while (result.next() != false) {
System.out.println("Username or password is incorrect.");
}
}
I also tidied up your code a bit to make it easier to read. You don't need backticks around your column names, because they are not reserved keywords (nor should they be).
Note: I'm not sure that your username and password columns are actually numeric. More likely, I would expect at least the username to be text of some sort. But, this would result in an error other than the one you reported in your question.

Java mysql - How to Update database from textbox

Can someone please tell me what is wrong to my query.
I have textbox to update the occupantname but it doesn't work, Only Status works.
String gOccupied = "Occupied" ;
String query = "UPDATE `rooms` SET `occupantname` = '"+txtFirstNames.getText()+"' , `status`='"+gOccupied+"' WHERE roomnumber = " +CBRoomNumber.getSelectedItem();
executeSQlquery(query,""+" Updated");
Can someone please tell me what is wrong to my query. i have textbox
to update the occupantname but it doesn't work, Only Status works.
Don't use direct MySql SQL with these special characters `
String query = "UPDATE rooms SET occupantname =
'"+txtFirstNames.getText()+"' , status='"+gOccupied+"' WHERE
roomnumber = " +CBRoomNumber.getSelectedItem();
Blockquote
Instated Use below SQL
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Main {
private static PreparedStatement preparedStmt = null;
private static Connection connection = null;
public static void main(String[] args) {
String gOccupied = "Occupied";
String occupantname = txtFirstNames.getText();
String query = "UPDATE rooms SET occupantname = ? , status= ? WHERE roomnumber = ?";
try {
executeSQlquery(query, occupantname, gOccupied, "Updated");
} catch (Exception e) {
e.printStackTrace();
}
}
private static void executeSQlquery(String query, String occupantname, String gOccupied, String status) throws SQLException {
try {
// create a java mysql database connection
String myDriver = "org.mysql.Driver";
String myUrl = "jdbc:mysql://localhost/test";
Class.forName(myDriver);
connection = DriverManager.getConnection(myUrl, "username", "password");
preparedStmt = connection.prepareStatement(query);
preparedStmt.setString(1, occupantname);
preparedStmt.setString(2, gOccupied);
preparedStmt.setInt(3, 101);
// execute the java preparedstatement
preparedStmt.executeUpdate();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
//finally block used to close resources
if (preparedStmt != null) {
connection.close();
}
if (connection != null) {
connection.close();
}
}
}
}
It is generally a terrible idea to construct SQL queries the way you currently do, as it opens the door to all sorts of SQL injection attacks. To do this properly, you'll have to use Prepared Statements instead. This will also resolve all sorts of escaping issues that you're evidently having at the moment.
SQL select statement with where clause

error on servlet when opening a jsp

im having a problem with my servlet whenever it was open from my JSP which is ShowPurchasingItems.jsp it will not go to the next JSP.
here is my ShowPurchasingItems.jsp
http://jsfiddle.net/0g3erumm/
and here is my Servlet that wont open my next JSP
package connection;
import java.io.*;
import java.sql.*;
import javax.servlet.http.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
#WebServlet("/CheckOutServlet")
public class CheckOutServlet extends HttpServlet
{
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
HttpSession session = request.getSession();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
String User = (String) session.getAttribute("username");
String id = (String) session.getAttribute("stockIdToPurchase");
float price = (float) session.getAttribute("UnitPriceToPurchase");
int stock = (int) session.getAttribute("OnStockToPurchase");
int quantityOrdered = (int) session.getAttribute("purchaseQuantity");
float totalPrice = price * quantityOrdered;
int newStock = stock - quantityOrdered;
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String url = "jdbc:mysql://localhost:3306/inventory";
String user = "root";
String password = "password";
String query = "INSERT INTO purchases (username,stockId,price,quantityOrdered,totalPrice) VALUES ('"+User+"', '"+id+"', "+price+", "+quantityOrdered+", "+totalPrice+");";
try
{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
rs = stmt.executeQuery(query);
if(rs.next())
{
String encodedURL = response.encodeRedirectURL("ShowInventoryList.jsp");
response.sendRedirect(encodedURL);
}
}
catch(Exception e)
{
out.println("There is an error here");
}
finally
{
out.close();
try
{
rs.close();
stmt.close();
conn.close();
}
catch (Exception e)
{
out.println("There is no error here");
}
}
}
}
it would keep on catching error on this statment out.println("There is an error here"); and i am stuck in here i dont know what else is wrong with my program hope someone can help me.
You're committing a cardinal sin by swallowing the exception and thus losing all information that may help you get to the bottom of your problem!
You should change how your exceptions are handled, at the very least you should be dumping the stacktrace:
catch(Exception e) {
out.println("There is an error here");
e.printStackTrace();
}
Once you have the stacktrace you'll be in a much better situation when it comes to diagnosing the problem (or asking more specific questions)!
Edit - Based on the exception posted in the comment:
java.sql.SQLException: Can not issue data manipulation statements with executeQuery()
Is being thrown because you are performing an update using the query method. You should change your code to this:
int updateCount = stmt.executeUpdate(query);
if(updateCount > 0) {
String encodedURL = response.encodeRedirectURL("ShowInventoryList.jsp");
response.sendRedirect(encodedURL);
}
executeQuery executes the given SQL statement, which returns a single ResultSet object.
You're making INSERT, which doesn't return anything. I suppose that's why you're getting an exception.
I'd recommend to use PreparedStatement where you can bind variables and prevent SQL injection + some DB work faster with prepared statements, and executeUpdate instead of executeQuery
PreparedStatement stmt = null;
...
String query = "INSERT INTO purchases (username,stockId,price,quantityOrdered,totalPrice) VALUES (?, ?, ?, ?, ?)";
stmt = conn.prepareStatement(query);
stmt.setString(1, username);
...
int inserted = stmt.executeUpdate();
if (inserted > 0) {
// there was a successfull insert
...
There are a lot of examples on the Internet. For example: http://www.mkyong.com/jdbc/how-to-insert-date-value-in-preparedstatement/

Display rows in database using java

I was trying to display the rows in the database using Java. My idea is to sort the rows in the database and display them in 3 columns and infinite rows. This is what I have. When I run it, I couldn't see any output. Where did I go wrong?
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.sql.SQLException;
public class Rows {
public static void main(String[] args) throws SQLException,ClassNotFoundException
{
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
String sql = "select * from site order by fname;";
stmt.execute(sql);
} catch (ClassNotFoundException e) {
System.err.println("Could not load database driver!");
} catch (SQLException e) {
e.printStackTrace();
}
finally
{
if (connection != null)
{
connection.close();
}
}
}
}
The database table I have is
datas(id int, fname varchar(20)
Statement stmt = connection.createStatement();
String sql = "select id, fname from site order by fname;";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()){
int id=rs.getInt("id");
.............
}
Reference: Retrieving and Modifying Values from Result Sets
The code should obtain a ResultsSet and iterate through it.
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/testapp";
String user = "root";
String password = "root";
connection = DriverManager.getConnection(url, user, password);
Statement stmt = connection.createStatement();
//You shouldn't need the semi-colon at the end
String sql = "select * from site order by fname;";
//missing piece
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println(id + "\t" + name);
}

Categories