import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.*;
import java.sql.*;
public class Login2 {
private Connection connection;
private JButton button1;
private JFrame frame;
private JLabel nameLabel,pwdLabel;
private JTextField nameTA,pwdTA;
private JPanel panel;
// private Statement stat;
private ResultSet rs;
public Login2()
{
String url = "jdbc:mysql://localhost:3306/(此處填寫妳創建的數據庫名字)";
String username = "(此處填寫妳的數據庫用戶,例如root)";
String password = "(此處填寫妳的數據庫安裝時設置的密碼)";
//加載驅動程序以連接數據庫
try {
Class.forName( "org.gjt.mm.mysql.Driver" );
connection = DriverManager.getConnection(
url, username, password );
}
//捕獲加載驅動程序異常
catch ( ClassNotFoundException cnfex ) {
System.err.println(
"裝載 JDBC/ODBC 驅動程序失敗。" );
cnfex.printStackTrace();
System.exit( 1 ); // terminate program
}
//捕獲連接數據庫異常
catch ( SQLException sqlex ) {
System.err.println( "無法連接數據庫" );
sqlex.printStackTrace();
System.exit( 1 ); // terminate program
}
frame = new JFrame();
panel = new JPanel();
panel.setLayout(new GridLayout(3,2));
nameLabel = new JLabel("user");
pwdLabel = new JLabel("password");
nameTA = new JTextField();
pwdTA = new JTextField();
button1 = new JButton("insert");
button1.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String str1 = nameTA.getText();
String str2 = pwdTA.getText();
String str = "insert into user values('"+str1+"','"+str2+"')";
try {
// Statement stat = null;
PreparedStatement pstmt = connection.prepareStatement(str);
pstmt.executeUpdate();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
JOptionPane.showMessageDialog(null, "yes");
}
});
panel.add(nameLabel);
panel.add(nameTA);
panel.add(pwdLabel);
panel.add(pwdTA);
panel.add(button1);
frame.add(panel);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setSize(300,100);
frame.setVisible(true);
}
/**
* @param args
*/
public static void main(String[] args) {
Login2 l = new Login2();
}
}
還有問題可以繼續聯系