Skip to Main Content

Null Pointer Exception: table Create USING MYSQL (If not exists")

User_AYF65May 11 2016 — edited May 12 2016

Hi,

i have written a code to create a table 7 to insert data in it. However I am getting a null pointer Exception. Table already exist & "create table if not exists" doesnt seem to work. Some body please guide me.

This is my code:

import java.sql.*;

public class InsertCreate {

   // JDBC driver name and database URL

   static final String JDBC_DRIVER = "com.mysql.jdbc.Driver"; 

   static  String DB_URL = "jdbc:mysql://localhost/STUDENTS";

   //  Database credentials

   static  String USER = "root";

   static  String PASS = "";

   //String sql="";

public static void main(String[] args) {

     

   Connection conn = null;

   Statement stmt = null;

   String sql="";

  

try{

   //STEP 2: Register JDBC driver

      Class.forName("com.mysql.jdbc.Driver");

  

   conn = DriverManager.getConnection(DB_URL,USER,PASS);

      //creating table

      sql = "CREATE TABLE if not exists REGISTRATION " +

                   "(id INTEGER not NULL, " +

                   " first VARCHAR(255), " +

                   " last VARCHAR(255), " +

                   " age INTEGER, " +

                   " PRIMARY KEY ( id ))";

     System.out.println("SSSSSSSSSSSSS");

      stmt.executeUpdate(sql);  //ThIS LINE GIVING ERROR!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

     System.out.println("QQQQQQQQQQQQQ");

      //inserting data

      sql = "Insert into registeration values (1, 'first1', 'last1', 20)";

      stmt.executeUpdate(sql);

     

      //STEP 6: Clean-up environment

     

      stmt.close();

      conn.close();

   }catch(SQLException se){

      //Handle errors for JDBC

      se.printStackTrace();

   }catch(Exception e){

      //Handle errors for Class.forName

      e.printStackTrace();

   }finally{

      //finally block used to close resources

      try{

         if(stmt!=null)

            stmt.close();

      }catch(SQLException se2){

      }// nothing we can do

      try{

         if(conn!=null)

            conn.close();

      }catch(SQLException se){

         se.printStackTrace();

      }//end finally try

   }//end try

   System.out.println("Goodbye!");

}//end main

}//end FirstExample


This is output of my program:

>javac InsertCreate.java

>java InsertCreate

SSSSSSSSSSSSS

java.lang.NullPointerException

        at InsertCreate.main(InsertCreate.java:49)

Goodbye!

>


Somebody please guide me.

Zulfi.

This post has been answered by User_AYF65 on May 12 2016
Jump to Answer
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked due to inactivity on Jun 9 2016
Added on May 11 2016
2 comments
872 views