gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 05:48:50 25 4
gpt4 key购买 nike

我正在尝试执行一个包含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 查询。有人可以帮我解决这个问题吗?

最佳答案

像这样(编辑 - 之后正确关闭资源):

//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();
}

}

关于java - 如何在java中的where子句中传递变量的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54329540/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com