I am trying to connect my backend endpoint code to a google cloud sql database. I have succesfully made and created the database and the tables using MySQL workbench. When i try to insert a new user in the user table i get a java.lang.NullPointerException when executing the query. See the code below:
@ApiMethod(name="registerUser")
public User addUser(@Named("name") String name, @Named("email") String email, @Named("rotation") double rotation,
@Named("p1email") String p1email, @Named("p2email") String p2email, @Named("password") String password) throws NotFoundException {
//Check if already exists
Connection conn = dbConnection.getConnection();
User u = null;
try {
String query = "SELECT * FROM users WHERE email = '"+email+"'";
java.sql.ResultSet rs = conn.createStatement().executeQuery(query);
if(rs != null){
throw new NotFoundException("User email is already used");
}else{
java.sql.PreparedStatement statement = conn.prepareStatement("INSERT INTO users (name,email,p1email,p2email,password,rotation) VALUES ( ?, ?, ?, ?, ?, ?)");
statement.setString(1, name);
statement.setString(2, email);
statement.setString(3, p1email);
statement.setString(4, p2email);
statement.setString(5, password);
statement.setDouble(6, rotation);
statement.execute();
}
String query2 = "SELECT * FROM users WHERE email = '"+email+"'";
java.sql.ResultSet rs2 = conn.createStatement().executeQuery(query2);
if(rs2 != null){
while(rs2.next()){
u = new User(rs2.getInt("id"), name, email, p1email, p2email, password, rotation);
}
}
}catch (SQLException e){
throw new NotFoundException(e);
}
return u;
}
The code to connect to the database is:
public java.sql.Connection getConnection(){
try{
Connection conn = DriverManager.getConnection(
"jdbc:google:mysql://your-project-id:your-instance-name/database",
"user", "password");
}catch(Exception e){
conn = null;
}
return conn;
}
I get the java.lang.NullPointerException in this sentence in the first code snippet:
java.sql.ResultSet rs = conn.createStatement().executeQuery(query);
The issue is most certainly that 'conn' is null by the time you get to this line. The reason for this being that an exception was thrown by DriverManager.getConnection and 'null' was returned explicitly by getConnection().
The question is now why did DriverManager.getConnection throw an exception? Since you are swallowing all exceptions and not logging anything, you can only try and guess. In general:
So the next step is to refactor your code to make it more debugging-friendly, get the exception details from the logs and work from there. If the reason is not apparent feel free to update the question with new info.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.