将javaprogram连接到mysql数据库

时间:2018-09-19 13:41:50

标签: java mysql

String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";

public void createConnection(int id, String name, String author, String 
    publisher) {
    try {
        Connection mycon = DriverManager.getConnection(dburl);
        Statement mystmt = mycon.createStatement();
        String sql = "insert into addbook" + "(Book ID,Book 
        Name,Author,Publisher)" + "values" + "(" + id + "," + name + "," + 
        author + "," + publisher + ")";

        mystmt.executeUpdate(sql);
        System.out.println("updated");
    } catch (Exception ex) {

    }

执行更新是另一个类中的一种方法。 这个代码段怎么了?数据库未更新!

3 个答案:

答案 0 :(得分:4)

您尚未加载数据库驱动程序,为此需要包含以下代码:

Class.forName("com.mysql.jdbc.Driver");

如果您没有驱动程序,请下载并放入项目库中。

答案 1 :(得分:2)

此代码段存在一些问题。一种是您未加载数据库。另外,您未使用用户名和密码

我建议您单独创建数据库连接。也许在单独的Java文件中。如下,

public class DatabaseConnection {
    public static Statement getConnection() throws Exception{
        Class.forName("com.mysql.jdbc.Driver"); //Loading the database
        Connection c = DriverManager.getConnection("jdbc:mysql://localhost:3307/restaurentsystem","nandika","nandika"); //username and password can save as variables and pass here

        Statement statement = c.createStatement();
        return statement;
    }
}

然后,您可以随时使用它。在这种情况下,

try {
    Statement s = DatabaseConnection.getConnection();
    s.executeUpdate("INSERT INTO addbook (Book ID, Book Name, Author, Publisher) VALUES (?, ?, ?, ?);"); //Values should assign here.
    System.out.println("updated");

} catch (Exception e) {
    System.out.println(e);
}

这就是我要做的。我建议您尝试这种方法。

答案 2 :(得分:0)

这是您应该执行的方法,并带有prepareStatement来防止注入

String dburl = "jdbc:mysql://localhost:3306/librarymanagementsystem";
String user = "nandika";
String password = "nandika";
private PreparedStatement preparedStatement;
private Connection con = null;


      public static void main(String[] args) {

}


public void createConnection(int id, String name, String author, String publisher) {
    try {




con = DriverManager.getConnection(dburl, user, password);
String stmt = "INSERT INTO addbook (Book ID,Book Name,Author,Publisher) VALUES (?, ?, ?, ?)";



            preparedStatement = con.prepareStatement(stmt);
            preparedStatement.setInt(1, id);
            preparedStatement.setString(2, name);
            preparedStatement.setString(3, author);
            preparedStatement.setString(4, publisher);
            preparedStatement.executeUpdate();
            con.close();

        System.out.println("updated");
    } catch (Exception ex) {

    }