使用Google App Engine端点连接到Cloud SQL

时间:2015-02-02 14:09:16

标签: java mysql database google-app-engine endpoint

我正在尝试将我的后端端点代码连接到google云sql数据库。我使用MySQL工作台成功创建并创建了数据库和表。当我尝试在用户表中插入新用户时,我在执行查询时得到java.lang.NullPointerException。请参阅以下代码:

@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;
}

连接数据库的代码是:

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;
}

我在第一个代码片段中的句子中得到了java.lang.NullPointerException:

 java.sql.ResultSet rs = conn.createStatement().executeQuery(query);

1 个答案:

答案 0 :(得分:0)

问题肯定是' conn'到达此行时为空。原因是DriverManager.getConnection和' null'抛出异常。由getConnection()显式返回。

现在的问题是为什么DriverManager.getConnection会抛出异常?由于您吞下所有异常并且没有记录任何内容,因此您只能尝试猜测。一般来说:

  1. 吞下所有异常都很糟糕。你应该只抓住那些 您打算处理的例外情况。
  2. 如果您发现异常,通常应该记录它。在这种情况下 你需要知道为什么DriverManager.getConnection引发了异常 首先。
  3. 因此,下一步是重构代码以使其更易于调试,从日志中获取异常详细信息并从那里开始工作。如果原因不明显,请随时用新信息更新问题。