MySQL连接数据库到Java

时间:2019-03-19 09:42:45

标签: java mysql

我无法连接到我的MySQL数据库,因此无法插入任何数据。我该如何解决这个问题?

这是我的代码:

public void actionPerformed(ActionEvent arg0) {
    try {
        Class.forName("com.mysql.jdbc.Driver");
        String query = "INSERT INTO tbl_login (id, tfname, password) VALUES (NULL,'" + tf.getText() + "', '" + pf1.getText() + "')";
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/prog", "root", null);
        Statement stmt = con.createStatement();
        ResultSet rs = stmt.executeQuery(query);

        java.sql.PreparedStatement = con.prepareStatement(query);
        JOptionPane.showMessageDialog(null, "Connected to Database ");
        rs.executeUpdate();

        info1 tbl_login = new info1();
        tbl_login.main(null);
        frame.dispose();

    } catch (SQLException e) {
        JOptionPane.showMessageDialog(null, "Cannot find Database Name ");
    } catch (ClassNotFoundException et) {
        JOptionPane.showMessageDialog(null, "Cannot find MySQL Driver ");
    }
}

1 个答案:

答案 0 :(得分:0)

使用Empty String代替null作为密码:

Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/prog","root","");