jdbc - java.lang.NullPointerException connecting to Cloud SQL -
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 jdbc se.printstacktrace(); } } catch (exception ex) { //handle errors class.forname ex.printstacktrace(); } //return connection object return con; } }
i created above class connect cloud sql instance in android studio above class returning null in turn hurts rest of code:
conn = connectionmanager.getconnection(); stmt = conn.createstatement(); string sql; sql = "insert messages (message) values('hello world')"; resultset rs = stmt.executequery(sql);
i'm not sure though why cam getting error:
caused by: java.lang.nullpointerexception: attempt invoke interface method 'java.sql.statement java.sql.connection.createstatement()' on null object reference
am missing imports or something?
com.mysql.jdbc.googledriver
only works if app running in appengine,and remember enable connector in appengine. if not use com.mysql.jdbc.driver.
the guide simple: https://cloud.google.com/appengine/docs/java/cloud-sql/#enable_connector_j
Comments
Post a Comment