我想编译一个名为FinalQuery的查询,但其中一部分必须在引号内。必须进入引号内的部分是一个字符串变量。
详细介绍 -
这是代码 -
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] =?必须在引号中提供。例如。在哪里[帐户名] =“约翰”。
目前我的查询是格式 -
SELECT xyz FROM pqr WHERE abc = variable name
即
SELECT status, count(status)
FROM main
WHERE [Account Name] = getaccountName (variable)
GROUP BY status;
我想将变量名称放在引号中,使其看起来像
SELECT xyz FROM pqr WHERE abc =“variable name”
SELECT status, count(status)
FROM main
WHERE [Account Name] = "getaccountName" (variable)
GROUP BY status;
请建议我如何让我的FinalQuery字符串变量在其中包含另一个变量的引号。
答案 0 :(得分:2)
但其中一部分必须在引号内。必须进入引号内的部分是一个字符串变量
使用PreparedStatment。它将使用正确的语法为您构建SQL,您可以轻松指定要使用的常量或变量:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, nameVariable );
stmt.setString( 2, "Title1" );
stmt.executeUpdate();