如何在Java的where子句中传递变量的值?

时间:2019-01-23 14:31:58

标签: java sql sql-server jdbc

我正试图执行一个包含where条件的sql查询。但是无论何时执行查询,它都会给我java.lang.NullPointerException。请帮助我!

我正在使用mssql和java

dbURL = "jdbc:sqlserver://ip:portnumber;databaseName=abc";
        username = "abc";
        password = "abc";

        //Load MS SQL JDBC Driver
        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
        con = DriverManager.getConnection(dbURL,username,password);

        //Creating statement object
        st = con.createStatement();
        selectquery = "select * from abc where TradeType = '"+tradepair+"'";
        rs = st.executeQuery(selectquery);

        while (rs.next()) {

            getpair = rs.getString("TradeType");
            dbTradePair.add(getpair);

        }
        System.out.println("Pairs :-"+dbTradePair);

当执行“ selectquery”时,我得到“ java.lang.NullPointerException”。 我希望我以正确的格式执行sql查询。有人可以帮我吗?

1 个答案:

答案 0 :(得分:1)

赞(编辑-之后正确关闭资源):

//Load MS SQL JDBC Driver
    try {

        Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");

    } catch (ClassNotFoundException e) {

        System.out.println(e.getMessage());

    }

    final String dbURL = "jdbc:sqlserver://ip:portnumber;databaseName=abc";
    final String username = "abc";
    final String password = "abc";

    Connection  con = null;
    PreparedStatement preparedStatement = null;
    final String selectquery = "select * from abc where TradeType = ?";
    try {
        con = DriverManager.getConnection(dbURL,username,password);
        preparedStatement = con.prepareStatement(selectquery);
        preparedStatement.setString(1, tradepair);

        // execute select SQL stetement
        ResultSet rs = preparedStatement.executeQuery();

        while (rs.next()) {

            String tradeType = rs.getString("TradeType");

            System.out.println("tradeType : " + tradeType);
        }

    } catch (SQLException e) {

        System.out.println(e.getMessage());

    } finally {

        if (preparedStatement != null) {
            preparedStatement.close();
        }

        if (con != null) {
            con.close();
        }

    }