get Nullpointerexception while insert records [duplicate] - java

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.

Related

Unable to connect database to server [duplicate]

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();
}
// ...

H2 in memory database multiple connections to same database

I am using h2 in memory database for testing. I have a situation where nested database calls will happen. Using h2 the connection is getting closed on the nested call, even if the objects are different.
ClassA:
Public class TestDb {
Public String getById(String id) {
try {
Connection conn= getConnection();
PreparedStatement ps = conn.prepareStatement(“query”);
ResultEntity rs = ps.executeQuery();
getOthersById(rs.get(id));
//here rs is closed and seering error as: object is closed
rs.get(2);
}Catch(Exception ex) {
//handle exceptions
}finally {
// close resultset
//close ps
// close conn
}
}
public int getOthersById(String id) {
try {
//get new connection
Connection conn= getConnection();
PreparedStatement ps = conn.prepareStatement(“query”);
ResultEntity rs = ps.executeQuery();
rs.get(id);
}Catch(Exception ex) {
//handle exceptions
}finally {
// close resultset
//close ps
// close conn
}
}
}
The problem in h2 is after the closing new connection and result set in getOthersById method, resultSet in getById is closed.
I am creating the h2 as below:
jdbc:h2:mem:test;DB_CLOSE_ON_EXIT=FALSE;DB_CLOSE_DELAY=-1;

Java code to connect to database won't set up connection [duplicate]

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.

Connection Java to sqlite (Netbeans)

I'm having a problem, not sure how to fix:
connection code:
public class sqliteConnection {
Connection conn = null;
public static Connection dbConnector() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:V:\\Database\\table.sqlite");
JOptionPane.showMessageDialog(null, "Conected to Database");
return conn;
}
catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
and where I'm using this connection:
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
try{
String sql="insert into test (test) value (?)";
PreparedStatement pst=conn.prepareStatement(sql);
pst.setString(1, Test.getText());
}catch (Exception e){
e.printStackTrace();
}
}
I'm getting a SQLITE_ERROR SQL error or missing database (near "value": syntax error) error, and I cant tell where the error could come from. I just created a test table in sqlite to test the connection, with one column which is a 'TEXT' named test. any help?

Getting null pointer exception in JDBC(mySql) program

I checked everything like username, password, db_url, table name, etc but still I get this output---connecting to database
creating statement
java.lang.NullPointerException
here is my code, (I'm using eclipse Kepler EE and MySQL 5.6.17.0)
import java.sql.*;
public class Demo {
static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
static final String DB_URL="jdbc:mysql://localhost/sample";
static final String USER="root" ;
static final String PASS="root";
public static void main(String[] args)
{
Connection conn=null;
Statement stmt=null;
try
{
Class.forName("com.mysql.jdbc.Driver");
System.out.println("connecting to database");
conn=DriverManager.getConnection(DB_URL, USER, PASS);
System.out.println("creating statement");
String sql="select * from sample";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next())
{
int eid=rs.getInt("id");
String ename=rs.getString("name");
System.out.print(eid+"\t");
System.out.print(ename);
System.out.println("");
}
rs.close();
stmt.close();
conn.close();
}catch(Exception e)
{
System.out.println(e);
}
finally
{
try
{
if(stmt!=null)
{
stmt.close();
}
}catch(Exception e)
{
System.out.println(e);
}
try
{
if(conn!=null)
{
conn.close();
}
}catch(Exception e)
{
System.out.println(e);
}
}
}
}
I don't think your statement is set. It is always null.
I think you should use this:
stmt = conn.createStatement( );
You didnt create stmt object
stmt = conn.createStatement( );
You have to add above line before this line ResultSet rs=stmt.executeQuery(sql);
You are executing query on a null object.
So getting NPE
You set Statement stmt=null; and you never initialize it later.

Categories