通过JDBC-ODBC将数据插入MS Access DB

时间:2014-04-17 09:11:03

标签: java jdbc

我尝试将一些数据从java插入到我的数据库(ms.access)但是当我点击按钮时没有添加到数据库。这是代码:

private void EmpButtonMouseClicked(java.awt.event.MouseEvent evt) {        
    String name,sex,email,username,password;
    name = tfName.getText();
    sex=(String) cbSex.getSelectedItem();
    email=tfEmail.getText();
    username=tfUser.getText();

    try{
        String url;
        url = "jdbc:odbc:mydata";
        Connection conn = DriverManager.getConnection(url,"",""); 
        Statement stm = conn.createStatement();
        stm.executeUpdate("INSERT INTO EmployeeLogin " + "VALUES (name, email, sex, username)");
        conn.close();
    }catch (SQLException sqlException){} 
} 

该代码有什么问题?

2 个答案:

答案 0 :(得分:1)

我想我找到了办法......

String sex=(String) cbSex.getSelectedItem();
    try{
        String url = "jdbc:odbc:mydata";
        Connection conn = DriverManager.getConnection(url,"","");
        String sql = "INSERT INTO CustomerLogin(Name, Email, Sex, Username, Password) VALUES(?,?,?,?,?)";     
pst=conn.prepareStatement(sql);
pst.setString(1, tfName.getText());
pst.setString(2, tfEmail.getText());
pst.setString(3, sex);
pst.setString(4, tfUser.getText());
pst.setString(5, pfPassword.getText());

pst.execute();
tfName.setText("");
tfEmail.setText("");
tfUser.setText("");
pfPassword.setText("");
JOptionPane.showMessageDialog(null,"Succed Create Account! You can now return to Login Page");


        }catch (Exception e){
        JOptionPane.showMessageDialog(null,e); }

答案 1 :(得分:0)

问题是:

stm.executeUpdate("INSERT INTO EmployeeLogin " + "VALUES (name, email, sex, username)");

写得像:

stm.executeUpdate("INSERT INTO EmployeeLogin VALUES ("+name+", "+email+", "+sex+", "+username+")");