你好我正在为我的java类做一个项目,用简单的话来说我必须做一个让你手工查询的程序,比如我把文本框示例" select * from table"它显示了结果,第二个问题是如果删除,更新或插入程序应该自动执行一个选择句子来显示结果。
public class InfoCd extends JFrame {
private JPanel contentPane;
private JTable table;
private JTextField textQuery;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
InfoCd frame = new InfoCd();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection conn=null;
/**
* Create the frame.
*/
public InfoCd() {
conn=sqliteConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 753, 477);
contentPane = new JPanel();
contentPane.setBackground(SystemColor.activeCaption);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnHacerConsulta = new JButton("Hacer Consulta");
btnHacerConsulta.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query="'?'";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, textQuery.getText());
ResultSet rs=pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
} catch (Exception e2) {
e2.printStackTrace();
}
}
});
btnHacerConsulta.setBounds(112, 388, 169, 39);
contentPane.add(btnHacerConsulta);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 0, 737, 367);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
textQuery = new JTextField();
textQuery.setFont(new Font("Arial", Font.BOLD | Font.ITALIC, 11));
textQuery.setHorizontalAlignment(SwingConstants.CENTER);
textQuery.setText("Escribir Consulta Aqui");
textQuery.setToolTipText("");
textQuery.setBounds(422, 388, 270, 39);
contentPane.add(textQuery);
textQuery.setColumns(10);
}
}
答案 0 :(得分:0)
通常,SQL看起来像:
String query = "Select * from TableName";
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
因此,如果您想使用文本字段中的查询动态执行此操作,请执行以下操作:
String query = textField.getText();
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery(query);
因此,用户可以在文本字段中键入正确的SQL查询。
阅读SQL Basics上的教程以获取更多信息。