我在按钮动作制作数据库中使用它,甚至连接了数据库,但信息没有进入数据库的表格。
private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhoast:3306//a","root","root");
Statement smt = conn.createStatement();
ps = conn.prepareStatement("insert into aone values (?,?,?)");
String n = name.getText();
String a = age.getText();
String r = roll.getText();
ps.setString(1,n);
ps.setString(2,a);
ps.setString(3,r);
int i = ps.executeUpdate();
if (i>0) {
JOptionPane.showMessageDialog(null, "data is saved");
}
else {
JOptionPane.showMessageDialog(null, "error");
}
}
catch(Exception e) {
}
}
答案 0 :(得分:1)
在catch块中打印堆栈跟踪。 JVM可能会抛出异常,但您永远不会这样知道。
当你这样做时,我确定你会被告知JDBC无法连接到" localhoast"。
我怀疑" localhoast"是正确的;试试" localhost"。
这段代码有很多问题:
试试这样:
private void jButtonActionPerformed(java.awt.event.ActionEvent evt) {
Connection conn = null;
PreparedStatement ps = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/a","root","root");
ps = conn.prepareStatement("insert into aone values (?,?,?)");
String n = name.getText();
String a = age.getText();
String r = roll.getText();
ps.setString(1,n);
ps.setString(2,a);
ps.setString(3,r);
int i = ps.executeUpdate();
if (i > 0) {
JOptionPane.showMessageDialog(null, "data is saved");
} else {
JOptionPane.showMessageDialog(null, "error");
}
} catch(Exception e) {
e.printStackTrace();
} finally {
close(ps); // You need to implement this
close(conn); // You need to implement this
}
}