开发者

connecting to database

开发者 https://www.devze.com 2023-03-10 08:07 出处:网络
can anyone help me how to connect my java forms to my mysql database? i have this following codes but it didn\'t work...

can anyone help me how to connect my java forms to my mysql database? i have this following codes but it didn't work...

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 {开发者_JAVA技巧
        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!");
    }
}                     


One problem I can see straight away is that your PreparedStatement expects 5 parameters (1 - 5) yet you're only setting 3! Secondly, I'm not sure why you use DriverManager.getConnection( url +db , ... ) when your database URL already contains a database name, so use just DriverManager.getConnection(url,user,pass). Having said that though, it would be good if you could clarify what exactly doesn't work?


There is problem with connection code :

url = jdbc:mysql://localhost:3306/Marketing
db  = Marketing

url + db = jdbc:mysql://localhost:3306/MarketingMarketing 

here you have to remove one extra marketing


The error is in this statement:

 con = DriverManager.getConnection(url + db, user, pass);

The getConnection method connect to database on url specified in 1st parameter. Here you combine 2 variables named url and db so your connection url will become: jdbc:mysql://localhost:3306/MarketingMarketing which may be not the thing you want. Use only url instead of url + db.

0

精彩评论

暂无评论...
验证码 换一张
取 消