public class Jdbc {
public static Connection getConn(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test"", "root", "root");
if (!conn.isClosed()) {
System.out.println("成功連接數據庫");
java.sql.PreparedStatement ps = conn.prepareStatement("select * from users");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println("id : " + rs.getInt(1) + " name : " + rs.getString(2) + " role : " + rs.getString(3)
這是連接數據庫的代碼
JButton button_3 = new JButton("查詢");
button_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
}
});
怎麼使輸入查詢信息後點擊這個按鈕使數據庫信息顯示出來
public void selectUser(){
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test"", "root", "root");
if (!conn.isClosed()) {
System.out.println("成功連接數據庫");
java.sql.PreparedStatement ps = conn.prepareStatement("select * from users");
ResultSet rs = ps.executeQuery();
while (rs.next()) {
System.out.println("id : " + rs.getInt(1) + " name : " + rs.getString(2) + " role : " + rs.getString(3)
" password: " + rs.getString(4)); }}} catch (Exception e) { e.printStackTrace(); } return conn; } }
}
接著:
JButton button_3 = new JButton("查詢");
button_3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
selectUser();
}
});