This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 6 years ago.
public class Actor {
String URL = "jdbc:mysql://localhost:3306/test/phone";
String USERNAME = "root";
String PASSWORD = "";
Connection connection = null;
PreparedStatement selectActors = null;
ResultSet resultSet = null;
public Actor(){
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
selectActors = connection.prepareStatement( "SELECT * FROM phone");
} catch (SQLException e) {
e.printStackTrace();
}
}
public ResultSet getActors() {
try {
resultSet = selectActors.executeQuery();
return resultSet;
} catch (SQLException e) {
e.printStackTrace();
}
return resultSet;
}
}
I'm trying to write Java code to connect to a database and display all the records in a table, but it won't work. The error I'm getting is a null pointer exception on getActors(). I've tried checking why the null pointer exception occurs but I just cannot get it.
Everything else works just fine
Replace ResultSet resultSet = null;
by ResultSet resultSet; to avoid the null pointer exception.
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
The infamous java.sql.SQLException: No suitable driver found
(21 answers)
Closed 11 days ago.
Unable to connect Postgres database to Tomcat 10.0.27 server
Here is DBConnection code:
public class DBConnection {
public static Connection getConnectionToDatabase() {
Connection connection = null;
try {
System.out.println("MySQL JDBC Driver Registered!");
connection = DriverManager.getConnection("jdbc:postgresql://localhost:5432/hplus", "postgres", "");
}
catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
}
if (connection != null) {
System.out.println("Connection made to DB!");
}
return connection;
}
}
Here is the code, where i try to get the connection:
public class ApplicationDao {
public List<Product> searchProducts(String searchString) {
Product product = null;
List<Product> products = new ArrayList<>();
try{
Connection connection = DBConnection.getConnectionToDatabase();
String sql = "select * from products where product_name like '%"+searchString+"%'";
Statement statement = connection.createStatement();
ResultSet set = statement.executeQuery(sql);
while(set.next()){
product= new Product();
product.setProductId(set.getInt("product_id"));
product.setProductImgPath(set.getString("image_path"));
product.setProductName(set.getString("product_name"));
products.add(product);
}
}
catch(SQLException exception){
exception.printStackTrace();
}
return products;
}
}
Here is what i get:
HTTP Status 500 – Internal Server Error
Type Exception Report
Message Cannot invoke "java.sql.Connection.createStatement()" because "connection" is null
I tried to debug the code but got no response. I looked on different forms what the problem is, but I did not find anything
The problem was in incorrect driver. Everything work out after adding this lines of code in DBConnection class:
try {
Class.forName("org.postgresql.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
// ...
I had a java app with mysql connection but i had to transfer my database to sqlite from mysql because of mysql can not be embedded, i have the connection but i get this exception when i am using the app.
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
I learnt this is a common mistake but i tried most of the answers however couldn't solve. The problem is i have about 30 different methods with void type or return types like these 2 for example below; (I call these methods on my swing app later)
I have these at start of my class;
private Connection con = null;
private Statement statement = null;
private PreparedStatement preparedstatement = null;
Methods for example;
public int lastPlaceProgram(){
String query= "Select * from userprogram where laststayed = 1";
try {
statement = con.createStatement();
ResultSet rs = statement.executeQuery(query);
int programid = 0;
while(rs.next()){
programid = rs.getInt("programid");
}
return programid;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return 0;
}
}
or
public String programType(int programid){
String query = "Select * from programs where id = ?";
try {
preparedStatement = con.prepareStatement(query);
preparedStatement.setInt(1, programid);
ResultSet rs = preparedStatement.executeQuery();
String type = "";
while(rs.next()){
type = rs.getString("type");
}
return type;
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
return null;
}
}
And constructor;
public Operations() {
String url = "jdbc:sqlite:C://Users//Me//Desktop//sqlited/trying.db";
try {
con = DriverManager.getConnection(url);
} catch (SQLException ex) {
Logger.getLogger(Operations.class.getName()).log(Level.SEVERE, null, ex);
}
}
I tried to add these finally block to after catch blocks of all my 30 methods;
finally{
try{
con.close();
} catch(Exception e){
}
}
But it didn't work, it gave Connection is closed mistake this time. I also tried to add preparedstatement.close(); to this finally block but didn't still work.
Finally blocks didn't work for me, i closed them manually if i had that variable to close. I mean if i used ResultSet and PreparedStatement at a method then i made rs.close() and preparedstatement.close() just before catch or before return. If i just had Preparedstatement variable on the method then i just did preparedstatement.close() before catch block or before return.
This question already has answers here:
Handling a null Connection in finally
(3 answers)
Closed 5 years ago.
I know a lot of similar topics exist about this error but I tried some suggestions and my problem is still not saved.
I'm following this tutorial: https://www.youtube.com/watch?v=B3gEbC37DAM&list=PL1A506B159E5BD13E&index=2
Here is my code:
public class JdbcDaoImpl {
public Circle getCircle(final int circleId) {
Connection conn = null;
try {
String driver = "org.apache.derby.jdbc.ClientDriver";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection("jdbc:derby//localhost:1527//db");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM circle where id= ?");
ps.setInt(1, circleId);
Circle circle = null;
ResultSet rs = ps.executeQuery();
if (rs.next()) {
circle = new Circle(circleId, rs.getString("name"));
}
rs.close();
ps.close();
return circle;
} catch (Exception e) {
throw new RuntimeException(e);
} finally {
try {
conn.close();
} catch (SQLException e) {
}
}
}
}
On "conn.close();" it says: Potential null pointer access. The variable may be null at this location.
And I have this error when i run the program: Exception in thread "main" java.lang.NullPointerException
I tried solutions i saw on similar topics like this one:
if(conn!=null){
conn.close();
}
but i still have errors.
Thank you in advance for your help !
Finally Block is always executed while you are using try catch, where you can get a potential NullPointerException is when conn = DriverManager.getConnection("jdbc:derby//localhost:1527//db"); throws NullPointerException which is caught by your catch (Exception e) and then finally block is starting to be executed where you do conn.close(), but your conn object is NULL which throws again NullPointerException which is not caught , cos you are catching catch (SQLException e)
You do not need to explicitly load the driver (Class.forName), assuming you are using Java >= 1.6.
You can use try-with-resources to manage the AutoCloseable objects (Connection, PreparedStatement, and ResultSet), so your code can be written as:
public Circle getCircle(final int circleId) {
try (Connection conn = DriverManager.getConnection("jdbc:derby//localhost:1527//db");
PreparedStatement ps = conn.prepareStatement("SELECT * FROM circle where id= ?")){
ps.setInt(1, circleId);
Circle circle = null;
try (ResultSet rs = ps.executeQuery()) {
if (rs.next()) {
circle = new Circle(circleId, rs.getString("name"));
}
}
return circle;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
This also guarantees all resources are closed properly, which solves a lot of issues that can arise because of resource leaks.
The problem was that getConnection could throw an Exception, leaving conn as null, which would cause a null pointer when you later tried to close it in the finally block.
The reason why conn can be null is simple. If code executed before conn is asigned, ie before this code runs successfully:
String driver = "org.apache.derby.jdbc.ClientDriver";
Class.forName(driver).newInstance();
conn = DriverManager.getConnection("jdbc:derby//localhost:1527//db");
this code has to run successfully for conn not to be null, therefore you need a non-null check before calling close() on it.
I am pretty new to Java so I'm working on a project to develop my knowledge with databases and Java.
I have figured out how to add queries into the database but now I'm getting errors when trying to print them out.
Assume I already have everything that's necessary imported in such as the scanner and sql statements
Here is my connection class which is named MainClass:
public static Connection getConnection() throws Exception {
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/testTable";
String username = "placeholder";
String password = "placeholder";
Class.forName(driver);
Connection conn = Driver Manager.getConnection(url, username, password);
return conn;
}
Now in a different class if the user types !lookup and a word I want the definition of that word to be retrieved from the table whose name is dictionary and columns are word, definition:
String userSearch = user_input.next();
String[] userSearchSplit = userSearch.split(" ", 3);
if (userSearchSplit[0].equals("!lookup")) {
try {
conn = MainClass.getConnection();
String query = "select definition from dictionary where word=" + userSearchSplit[1];
ResultSet result = pstmt.executeQuery(query);
while (result.next()) {
String definition = result.getString("definition");
System.out.println(definition);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
At the end of all this when I try to look up a word I put in the table before running I get:
java.lang.NullPointerException
Check if your user_input is null?
I am assuming your code:
ResultSet result = pstmt.executeQuery(query);
as
Statement pstmt = conn.createStatement();
ResultSet result = pstmt.executeQuery(query);
Or it could be that you have not initialized the pstmt properly
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
I trying to insert data to my database using prepare statements but I get Nullpointerexception
My Database connection code
public class DBConnect {
Connection conn=null;
public static Connection connecrDb(){
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:E:\\NetBeansProjects\\Abdo`s Project\\project.sqlite");
System.out.println("connection success");
conn.setAutoCommit(false);
return conn;
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
and my code in Main Class
public class Items extends javax.swing.JFrame {
Connection conn =null;
ResultSet rs = null;
PreparedStatement pst=null;
public Items() {
initComponents();
DBConnect.connecrDb();
}
private void SaveBtnActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql = "INSERT INTO test (name) values(?)";
pst=conn.prepareStatement(sql);
pst.setString(1,item_name.getText() );
pst.executeUpdate();
conn.commit();
}
catch(Exception e ){
System.out.println(e);
System.out.println(e.getStackTrace());
}
}
Output is
java.lang.NullPointerException
[Ljava.lang.StackTraceElement;#7da469fe
what is wrong in my code ?
conn is null in SaveButtonActionPerformed. Initialize it in the Item class:
public class Items extends javax.swing.JFrame {
Connection conn = DriverManager.getConnection("jdbc:sqlite:E:\\NetBeansProjects\\Abdo`s Project\\project.sqlite");
You can also initialize it inside your method, but just be sure to initialize it before you use it.