简体   繁体   中英

My Select Query with where clause not working

I am trying to fetch data from postgres database using where clause. It is returning null values. But running the same query in postgres worksheet, it is giving the datas.

And one more thing, I cannot able to use without double quotes(\\"USER_INFO\\"),while using without double quotes I am getting the error "column name does not exist".

But most of the online examples are without double quotes only.

Please help on this to resolve. Thanks in advance.

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

When column contains "null" as data. It gives null only. Try to insert some data using insert query and after that we can try to fetch.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM