Reputation: 1425
I want to compile a query called 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.
To go into more detail -
Here is the code -
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);
}
}
But in a SQL query the WHERE [XYZ] = ? has to be provided in quotes. Eg. WHERE [Account Name] = "John".
Currently my query is a format -
SELECT xyz FROM pqr WHERE abc = variable name
i.e.
SELECT status, count(status)
FROM main
WHERE [Account Name] = getaccountName (variable)
GROUP BY status;
I want to put variable name in quote marks so that it looks like
SELECT xyz FROM pqr WHERE abc = "variable name"
SELECT status, count(status)
FROM main
WHERE [Account Name] = "getaccountName" (variable)
GROUP BY status;
Please suggest how I can make my FinalQuery string variable have quotes around another variable inside it.
Upvotes: 0
Views: 1163
Reputation: 324118
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
Use a PreparedStatment. It will build the SQL for you using the proper syntax and you can easily specify constants or variables to be used:
String sql = "INSERT INTO Page (Name, Title) VALUES (?, ?)";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, nameVariable );
stmt.setString( 2, "Title1" );
stmt.executeUpdate();
Upvotes: 2