Null pointer exception while execution a jdbc code in net beans? [closed] - java

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 7 years ago.
Improve this question
i m connecting ms access to odbc and odbc to javacode.
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
*
* #author aditya
*/
public class Odbc {
/**
* #param args the command line arguments
*/
public static void main(String[] args) {
Connection con=null;Statement st=null;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
System.out.println("driver loaded");
} catch (ClassNotFoundException ex) {
System.out.println(ex);
}
try {
con=DriverManager.getConnection("jdbc:odbc:studentdsn");
} catch (SQLException ex) {
Logger.getLogger(Odbc.class.getName()).log(Level.SEVERE, null, ex);
}
try {
Statement St = con.createStatement();
String sql="insert into Student values(111,gfhgf,kjhk,123,jgfj)";
int n;
n=st.executeUpdate(sql);
here.. i m getting runtime error. deferencing null pointer.
} catch (SQLException ex) {
System.out.println(ex);
}
}
}

You have two Statement type variables. One which you defined as null:
Statement st=null;
and one which was actually initialized ("s" is uppercase here):
Statement St = con.createStatement();
then you are calling a function on the null variable:
n=st.executeUpdate(sql);

You have defined con as null and then you try to initialize it like:
try {
con=DriverManager.getConnection("jdbc:odbc:studentdsn");
} catch (SQLException ex) {
Logger.getLogger(Odbc.class.getName()).log(Level.SEVERE, null, ex);
}
Now if you get exception while creating connection, your connection would still be null and then you try to use null connection to create statement as below:
try {
Statement St = con.createStatement();
And hence null pointer exception.
Create all the JDBC connection related statement in one try catch block and most importantly find out why connection creation failed.

Related

Why does executeUpdate() function not work? Give steps to solve in a normal project rather than a maven based project [duplicate]

This question already has an answer here:
Caused by: java.lang.NoSuchMethodError: org.postgresql.core.BaseConnection.getEncoding()Lorg/postgresql/core/Encoding;
(1 answer)
Closed 4 years ago.
CODE:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package aaa;
import static aaa.DB.geom;
import static aaa.DB.getConnection;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCExample {
public static void main(String[] argv) throws SQLException {
try {
Class.forName("org.postgresql.Driver");
// Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("Where is your PostgreSQL JDBC Driver? " +
"Include in your library path!");
e.printStackTrace();
return;
}
System.out.println("PostgreSQL JDBC Driver Registered!");
Connection connection = null;
try {
connection = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/postgres", "postgres",
"abc");
} catch (SQLException e) {
System.out.println("Connection Failed! Check output console");
e.printStackTrace();
return;
}
if (connection != null) {
System.out.println("You made it, take control your database now!");
//Connection conn = getConnection();
connection.setAutoCommit(false);
Statement s = null;
try {
s = connection.createStatement();
} catch (Exception e) {
System.out.println("statmnt connection not works");
}
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ss.executeUpdate();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
String query = "CREATE TABLE COMPANY(ID INT );";
ResultSet r = s.executeQuery(query);
connection.commit();
} else {
System.out.println("Failed to make connection!");
}
}
}
RUN:
-------- PostgreSQL JDBC Connection Testing ------------
PostgreSQL JDBC Driver Registered!
You made it, take control your database now!
Exception in thread "main" java.lang.NoSuchMethodError:
org.postgresql.core.BaseConnection.getPreferQueryMode()Lorg/postgresql/jdbc/PreferQueryMode;
at org.postgresql.jdbc.PgPreparedStatement.executeWithFlags(PgPreparedStatement.java:151)
at org.postgresql.jdbc.PgPreparedStatement.executeUpdate(PgPreparedStatement.java:132)
at aaa.JDBCExample.main(JDBCExample.java:69)
C:\Users\Dell\AppData\Local\NetBeans\Cache\8.2\executor-snippets\run.xml:53: Java returned: 1
BUILD FAILED (total time: 0 seconds)
QUESTION:Give me steps to solve it since database is connected already! What is the core of the problem?
The problem is that if database postgresql connected then why not insert into database. The tables are also available and seen from netbeans. There needs to be a way to solve this run time exception issue when there is a query execution... So I needed step by step details to make it correct.
A SELECT statements has to be executed using executeQuery(). executeUpdate() is for DML statements like UPDATE, INSERT, or DELETE that don't normally return a ResultSet. Also, a DDL statement like CREATE TABLE can not be executed using executeQuery() you need execute() or executeUpdate() for that.
So your code should be:
PreparedStatement ss = connection.prepareStatement("SELECT * FROM nodes_road_geoms");
try {
ResultSet rs = ss.executeQuery();
while (rs.next() {
// do something
}
rs.close();
} catch (Exception e) {
System.out.println("statmnt excute update connection not works: ");
e.printStackTrace();
}
And:
String query = "CREATE TABLE COMPANY(ID INT );";
s.execute(query);
connection.commit();
You have connection.setAutoCommit(false); and you didnt commit after performing update. You have to commit your transaction in order for changes to apply. You can also setAutoCommit(true);

Potential null pointer access. The variable may be null at this location. java.lang.NullPointerException [duplicate]

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.

Result Set resource leak even though I am closing the RS?

I am getting 'Resource leak: 'rsHP' is not closed at this location' everywhere I use a rsHP = stmt.executeQuery(query);
Here is a basic layout of what this method does...
public static void method(String x, Connection conn){
Statement stmtHP = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rsHP = null;
try{
----ALGORITHM IN HERE------
****This is the general form of this method*****
queryHP = "select * from SOMETABLE where SOMETHING = 'blah'";
rsHP = stmtHP.executeQuery(queryHP);
while(rsHP.next()){
List.add(rsHP.getString("COLNAME"));
}
.
.
repeats for 8 different queries
.
.
queryHP = "select * from SOMEOTHERTABLE where SOMETHINGELSE = 'blah2'";
rsHP = stmtHP.executeQuery(queryHP);
while(rsHP.next()){
List.add(rsHP.getString("NEWCOLNAME"));
}
}catch(Exception e){
System.out.println("Hey dumbo you suck, Exception Found");
rsHP.close();
stmtHP.close();
conn.close();
}finally{
rsHP.close();
stmtHP.close();
// connection gets closed later if no exceptions thrown
}
}// end method
At the end here I am clearly closing all my stuff. I am confused as to how I have a memory leak if it is literally impossible for my method to terminate without closing the RS outside of an error being thrown.
Connection#createStatement() throws an SQLException so this code would not compile at all.
I suggest you change the signature of the method to
public static void method(String x, Connection conn) throws SQLException
For the resource leak, I guess using the following logic will help you
try{
// code
rsHP.close();
conn.close();
}catch(Exception e){
// StackTrace
}finally{
if (rsHP != null) rsHP.close();
if (conn != null) conn.close();
}

Can return connection object inside a try with resources

I have connection provider class as bleow to return connection.
public class ConnectionProvider {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection ConnectDB() throws ClassNotFoundException, SQLException {
try (Connection connection = DriverManager
.getConnection("jdbc:mysql://localhost:3306/jspservlet_test","root", "root");
) {
return connection;
}
}
}
Here is main method to call connection provider.
public void Test() {
try {
Connection con = ConnectionProvider.ConnectDB();
PreparedStatement ps = con.prepareStatement("");
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
But "com.mysql.jdbc.exceptions.jdbc4.MySQLNonTransientConnectionException: No operations allowed after connection closed." error are always show at below line of code.
PreparedStatement ps = con.prepareStatement("");
Because, according to Oracle documentation, If use try with resources java 7 features, resources are auto close after try block even it's errors occurred or not. So even I returned the connection it's already closed.
Let me know, my usage logic is wrong?
How can I return this connection inside try with resource?
I tried many time googling for solution but does not get convenience answers for me.
Let me know your suggestion and feedback please.
What you can't do...
With a try-with-resources as you have it after you return the connection you return(d) is close(d). You can't return the connection from inside the try with resources.
What you can do...
Pass the connection (inside your try-with-resources) to a method that takes a connection. You can also use a ConnectionPool, and get the Connection when you need it (to create and execute a query).
Let me know, my usage logic is wrong?
The usage of 'try-with-resources' logic is wrong in this context, because the intention of ConnectDB() is to return a connection instance which could be actually used by the caller to send a SQL statement, but instead, the connection instance is getting auto-closed, before it could be used by the caller, because of using 'try-with-resources' construct of Java.
Quick how-to on try-with-resource and JDBC
Your ConnectionProvider's ConnectDB already declares it is throwing SQLException - so no need to catch it in here: (You should consider replacing this code with connection pool maybe)
public class ConnectionProvider {
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection ConnectDB() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/jspservlet_test","root", "root");
}
}
Instead use try-with-resource in your test-class to clean up your code and focus on errors your SQL code
might have:
public void Test() {
try (Connection con = ConnectionProvider.ConnectDB();
PreparedStatement ps = con.prepareStatement("SELECT 1")) {
//Prepare your Statement
ps.setInt(1, 1);
//And another try-with-resource for the result - note the closing brace
try(ResultSet rs = ps.executeQuery()) {
while(rs.next()) {
//Handle your Result
System.out.println(rs.getString(1));
}
} // This closes try-with-resource. Exception will be rethron to be caught in outer catch!
} catch (SQLException e) {
//SQL is Broken - but only ONE catch to catch them all
e.printStackTrace();
}
}
That way you gain
Better readability for your code (no calls to close surrounded by finally and if != null)
Centralized error handling if anything in your SQL code breaks (so you can focus on functional error of "statement didn't run")
Better code quality: No need to worry about Cursors, Statements, Connections not being propery closed.

insert "Finally" to complete the code [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
i hav written a program in java using both get and set method....but it does not give me the desired output it tells insert finally block my code is given below..in the console of eclipse it shows only connected but no values of table displayed
package com.glomindz.mercuri.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.glomindz.mercuri.pojo.User;
import com.glomindz.mercuri.util.MySingleTon;
public class UserServicesDAO {
private Connection connection;
public UserServicesDAO() {
// connection = new MySingleTon().getConnection();
connection = MySingleTon.getInstance().getConnection();
}
public List<User> get_all_data() {
List<User> usersList = new ArrayList<User>();
String query = "SELECT * FROM spl_user_master";
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
usersList.add(user);
}
}
}
public List<User> set_all_data() {
List<User> usersList = new ArrayList<User>();
try {
PreparedStatement stmt = connection.prepareStatement("INSERT INTO spl_user_master(name,email,mobile,password,role,status,last_update)VALUES(?,?,?,?,?,?,?)");
stmt.setString(1, "Charlie Sheen");
stmt.setString(2, "help#glomindz.com");
stmt.setString(3, "9554087107");
stmt.setString(4, "cbf91a71c21d5ec348b0c749b2f0055k");
stmt.setString(5, "user");
stmt.setString(6, "3");
stmt.setString(7, "2013-07-02 22:05:16");
boolean execute = stmt.execute();
System.out.println(execute);
stmt.getResultSet();
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return usersList;
}
public static void main(String[] args) {
UserServicesDAO userdao = new UserServicesDAO();
List<User> data = userdao.get_all_data();
List<User> data1 = userdao.set_all_data();
System.out.println(data);
System.out.println(data1);
System.exit(0);
}
}
whats wrong with the code plz specify
In java, try block must be followed either by a catch or a finally block. In your code you have the below try block, which is not followed by a catch/finally block(s).
try {
PreparedStatement stmt = connection.prepareStatement(query);
boolean execute = stmt.execute();
System.out.println(execute);
ResultSet resultSet = stmt.getResultSet();
System.out.println(resultSet.getMetaData());
while (resultSet.next()) {
User user = new User();
user.setId(resultSet.getInt("id"));
user.setName(resultSet.getString("name"));
user.setEmail(resultSet.getString("email"));
user.setMobile(resultSet.getString("mobile"));
user.setPassword(resultSet.getString("password"));
user.setRole(resultSet.getString("role"));
user.setStatus(resultSet.getString("status"));
user.setLast_udpate(resultSet.getString("last_update"));
usersList.add(user);
}
} // missing catch/finally statements
You can either add a catch block to handle any exception happening in the above try block code or put a finally block. The general construct for a try block is
try {
code
}
catch and finally blocks . . .
Learn more about java exception handling here: http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
You can not have only try{ } in Java. try { } block must be followed by either catch{ } or finally{ }.
So here you should use either catch{ } or finnaly{ } for code utilization.
try{
....
....
}finally{
//cleanup
}
try{
....
....
}catch(Exception e)
{
....
....
}
You can also refer this :
http://docs.oracle.com/javase/tutorial/essential/exceptions/handling.html
You need a catch block if you want to catch exceptions.
try {
....
} catch (Exception e) {
....
}
If you use try and finally combination, note that try is there only to allow finally.
You don't assign stmt.getResultSet(); to anything! UserList is an empty list as nothing is added to it. You need to add the results of stmt.getResultSet(); to the list.
For finally: The code block in finally will be executed for sure - but it is NOT sure when! Use finally to close database connections or other clean up work. Or better, do not use it at all. http://my.safaribooksonline.com/book/programming/java/9780137150021/creating-and-destroying-objects/ch02lev1sec7
Use a catch block to catch errors
You can not have a try block only. To have a try block you must have at least one catch block or a finally block

Categories