So I'm supposedly connected to JDBC, using mySQL. I have a connection function, which tells me that it works fine. But I run into a problem in the PreparedStatement code.
My actual code does not show any errors but when I run, my terminal shows me "Database connection success" then gives me "Exception in thread "main" java.lang.NullPointerException".
Which directs me to my line -- PreparedStatement posted = conn.prepareStatement("INSERT INTO people(firstName, lastName) VALUES ('"+var1+"', '"+var2+"')")
So there is a disconnect when running my post(); And that does not make any sense to me....What should I check to fix this?
public static void main(String[] args) throws Exception{
People project = new People();
project.createConnection();
project.post();
}
void createConnection(){
try {
String driver = "com.mysql.cj.jdbc.Driver";
Class.forName(driver);
java.sql.Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/peopledb", "root", "root");
if(conn != null){System.out.println("Database connection success");}
} catch (ClassNotFoundException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE, null, ex);
} catch (SQLException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE, null, ex);
}
}
void post() {
try {
final String var1 = "John";
final String var2 = "Doe";
PreparedStatement posted = conn.prepareStatement("INSERT INTO people(firstName, lastName) VALUES ('"+var1+"', '"+var2+"')");
posted.executeUpdate();
if(conn != null){
System.out.println("Insert Completed");
}
} catch (SQLException ex) {
Logger.getLogger(People.class.getName()).log(Level.SEVERE, null, ex);
}
}
}