【问题标题】:My Select Query with where clause not working带有 where 子句的我的选择查询不起作用
【发布时间】:2019-04-18 01:18:45
【问题描述】:

我正在尝试使用 where 子句从 postgres 数据库中获取数据。它返回空值。但是在 postgres 工作表中运行相同的查询,它会给出数据。

还有一件事,我不能在没有双引号的情况下使用(\“USER_INFO\”),而在没有双引号的情况下使用我收到错误“列名不存在”。

但是网上大部分例子都是没有双引号的。

请帮助解决这个问题。提前致谢。

    public class PostGreDB {
static final String JDBC_DRIVER = "org.postgresql.Driver";
    static final String DB_URL = "jdbc:postgresql://localhost:5432/";

public static void main(String[] args) throws SQLException
{
Connection conn = null;
//Statement st = null;
try{
    //STEP 2: Register JDBC driver
    Class.forName("org.postgresql.Driver");

    //STEP 3: Open a connection
    System.out.println("Connecting to database...");
    conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/","postgres","XXXX@1904");

    //STEP 4: Execute a query
    System.out.println("Creating statement...");
    //st = conn.createStatement();
    String sql;
    sql = "SELECT * FROM public." + "\"USER_INFO\" where \"USER_INFO\".\"EMAIL_ID\" = ?";
    System.out.println(sql);
    try(PreparedStatement pst= conn.prepareStatement(sql)){
        pst.setString(1 , "cppandi33@gmail.com");
        pst.executeQuery();

    try(ResultSet rs = pst.getResultSet()){
    //STEP 5: Extract data from result set
    while(rs.next()){
        //Retrieve by column name
        String first = rs.getString("USER_ID");
        String last = rs.getString("USER_NAME");
        String email = rs.getString("EMAIL_ID");

        //Display values
        System.out.print("User ID: " + first+"\n");
        System.out.println("User Name: " + last+"\n");
        System.out.println("Email: " + email);
    }
    rs.close();
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    }catch (Exception e) {
        // TODO: handle exception
        e.printStackTrace();
    }
    //STEP 6: Clean-up environment

   // st.close();
    conn.close();
}catch(SQLException se){
    //Handle errors for JDBC
    se.printStackTrace();
}catch(Exception e){
    //Handle errors for Class.forName
    e.printStackTrace();
}
finally
{
    try{
        if(conn!=null)
            conn.close();
    }
    catch(SQLException se){
        se.printStackTrace();
    }//end finally try
}
}
}

【问题讨论】:

  • 你为什么首先使用LIKE?您是否希望电子邮件是 EMAIL_ID 的子字符串?
  • 感谢您的即时回复@Tim Okay EMAIL_ID =?也只得到相同的空值。
  • 那么你应该检查你的表数据。我觉得这个查询很好。
  • 谢谢@TimBiegeleisen,数据库中的值似乎是“null”。现在我插入了一些值。它工作正常。

标签: java postgresql jdbc


【解决方案1】:

当列包含“null”作为数据时。它只给出空值。尝试使用插入查询插入一些数据,然后我们可以尝试获取。

【讨论】:

    猜你喜欢
    • 2011-07-05
    • 1970-01-01
    • 2015-10-25
    • 2019-08-27
    • 2022-06-17
    • 2017-08-24
    • 1970-01-01
    • 2020-08-18
    • 1970-01-01
    相关资源
    最近更新 更多