任何人都可以幫助我如何將我的Java表單連接到我的MySQL數據庫? 我有這個以下代碼,但它沒有工作...連接數據庫
private void saveActionPerformed(java.awt.event.ActionEvent evt) {
String value1 = textField1.getText();
String value2 = textField2.getText();
String value3 = textField3.getText();
String value4 = textField4.getText();
Connection con = null;
String url = "jdbc:mysql://localhost:3306/Marketing";
String driver = "com.mysql.jdbc.Driver";
String db = "Marketing";
String user = "root";
String pass = "";
System.out.println(value1 + value2 + value3 + value4);
try {
Class.forName(driver);
con = DriverManager.getConnection(url + db, user, pass);
PreparedStatement st = con.prepareStatement("insert into clients (idclients, name, address, contact_person, contact_num) values(?,?,?,?,?)");
st.setString(2, value2);
st.setString(3, value3);
st.setString(4, value4);
st.executeUpdate();
JOptionPane.showMessageDialog(jPanel1, "Data is successfully inserted into database.");
con.close();
} catch (Exception e) {
JOptionPane.showMessageDialog(jPanel1, "Error in submitting data!");
}
}
你會得到什麼錯誤? – sfat 2011-06-03 09:08:43
「不工作」是什麼樣子?幫助我們幫助你 - 提供一些有價值的信息。我建議您重構該代碼以從Swing中分離SQL。正如所寫,這段代碼不會很有用。 – duffymo 2011-06-03 09:09:29
作爲一個評論...處理事件時打開數據庫連接是非常不好的做法。隔離這段代碼並重用它...查看DAO模式。 – 2011-06-03 09:11:03