import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
public class ConnectionManager {
private static String URL = "jdbc:google:mysql://your-project-id:your-instance-name/database";
private static String DRIVER = "com.mysql.jdbc.GoogleDriver";
private static String USERNAME = "root";
private static String PASSWORD = "test";
private static Connection CON = null;
public static Connection getConnection() {
try {
Class.forName(DRIVER);
try {
CON = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
}
} catch (Exception ex) {
//Handle errors for Class.forName
ex.printStackTrace();
}
//return a connection object
return CON;
}
}
I created the above class to connect to my Cloud SQL instance in Android Studio but the above class is returning a NULL which in turn hurts the rest of my code:
conn = ConnectionManager.getConnection();
stmt = conn.createStatement();
String sql;
sql = "INSERT into messages (message) VALUES('Hello World')";
ResultSet rs = stmt.executeQuery(sql);
I'm not sure though why I cam getting this error:
Caused by: java.lang.NullPointerException: Attempt to invoke interface method 'java.sql.Statement java.sql.Connection.createStatement()' on a null object reference
Am I missing some imports or something?
Class.forName(DRIVER);You don't use the return value of that method call... Are you getting anySQLExceptions or anything else during that method call?