اینم یه کد که کامل کار میکنه و فکر کنم اصولی باشه:
import java.awt.FlowLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JTextField;
public class TestDB extends JFrame {
private JButton addDB;
private JTextField tx1, tx2;
public TestDB() {
super("Test Dabatbase");
setDefaultCloseOperation(EXIT_ON_CLOSE);
try {
Class.forName("org.h2.Driver");
} catch (ClassNotFoundException ex) {
ex.printStackTrace();
}
tx1 = new JTextField();
tx1.setColumns(10);
tx2 = new JTextField();
tx2.setColumns(10);
addDB = new JButton("Click to add");
addDB.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
try {
Connection con = DriverManager.getConnection("jdbc:h2:~/test", "sa", "");
Statement s = con.createStatement();
s.execute("INSERT INTO std_info" + " (LastName,FirstName)" + " VALUES ('" + tx1.getText()
+ "','" + tx2.getText() + "')");
s.close();
con.close();
JOptionPane.showMessageDialog(null, "one row added", "ok", JOptionPane.INFORMATION_MESSAGE);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
});
add(tx1);
add(tx2);
add(addDB);
}
public static void main(String args[]) {
TestDB testdb = new TestDB();
testdb.setLayout(new FlowLayout(FlowLayout.CENTER));
testdb.setSize(160, 130);
testdb.setVisible(true);
}
}