javaprogram与mysql数据库的连接

daolsyd0  于 2021-06-19  发布在  Mysql
关注(0)|答案(3)|浏览(287)
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) {

    }

execute update是另一个类中的一个方法。这个代码段似乎有什么问题?数据库没有更新!!

yk9xbfzb

yk9xbfzb1#

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

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

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

nuypyhwy

nuypyhwy2#

这是你应该做的,准备好的声明,以防止注射

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) {

    }
v7pvogib

v7pvogib3#

他们发现这个代码片段有一些问题。一是你没有加载数据库。你也没有使用用户名和密码。
我建议您单独创建数据库连接。可能在一个单独的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);
}

如果我这么做,我会这么做。我建议你试试这个方法。

相关问题