我想编译一个名为 FinalQuery 的查询,但其中一部分必须位于引号内。引号内的部分是字符串变量。
了解更多细节 -
- 将此 FinalQuery 查询提供给 JFreeChart 以制作饼图。
- 但 FinalQuery 是根据用户的特定选择在程序中编译的。
- 用户的选择是在 JComboBox 中做出的。
这是代码 -
public class Execute extends JFrame {
private JComboBox comboAccountName = new JComboBox();
public Execute() {
....................
getContentPane().add(comboAccountName);
comboAccountName.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CompileQuery();
}
});
final String query = CompileQuery(); //variable query is executed in JFreeChart
JButton btnDraw = new JButton("Draw");
btnDraw.setFont(new Font("Segoe UI Symbol", Font.BOLD, 15));
btnDraw.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
JDBCPieDataset hdataset = new JDBCPieDataset(DatabaseConnection.ConnectDB(), query);
JFreeChart chart = ChartFactory.createPieChart("Query",
hdataset, true, true, false);
...............}
String CompileQuery()
{
String getAccountName = (String)comboAccountName.getSelectedItem();
String FinalQuery = "SELECT status, COUNT(status) FROM main WHERE [Account Name] = "+getAccountName+" GROUP BY status";
System.out.println(FinalQuery);
return FinalQuery;
};
public static void main(String[] args) {
Execute frame1 = new Execute();
frame1.setVisible(true);
}
}
但是在 SQL 查询中,WHERE [XYZ] = ?必须在引号中提供。例如。 WHERE [帐户名称] =“约翰”。
目前我的查询是一种格式 -
从 pqr 中选择 xyz,其中 abc = 变量名称
即
SELECT status, count(status)
FROM main
WHERE [Account Name] = getaccountName (variable)
GROUP BY status;
我想将变量名称放在引号中,使其看起来像
从 pqr 中选择 xyz,其中 abc =“变量名称”
SELECT status, count(status)
FROM main
WHERE [Account Name] = "getaccountName" (variable)
GROUP BY status;
请建议我如何使 FinalQuery 字符串变量在其中的另一个变量周围加上引号。
最佳答案
but a part of it has to be inside quote marks. And the part that has to go inside the quote marks is a string variable
使用PreparedStatement。它将使用正确的语法为您构建 SQL,并且您可以轻松指定要使用的常量或变量:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, nameVariable );
stmt.setString( 2, "Title1" );
stmt.executeUpdate();
关于java - 在字符串中的变量周围包含引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22049503/