亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

將java程序連接到mysql數據庫

將java程序連接到mysql數據庫

素胚勾勒不出你 2021-09-29 11:02:01
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 是另一個類中的一個方法。這個代碼段似乎有什么問題?數據庫不更新??!
查看完整描述

3 回答

?
浮云間

TA貢獻1829條經驗 獲得超4個贊

您尚未加載數據庫驅動程序,要執行此操作,請包含以下代碼:

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

如果您還沒有驅動程序下載并放入項目庫。


查看完整回答
反對 回復 2021-09-29
?
倚天杖

TA貢獻1828條經驗 獲得超3個贊

他們是這個代碼片段的一些問題。一是你沒有加載數據庫。你也沒有使用 username 和 password。


我建議您單獨創建數據庫連接。也許在一個單獨的 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);

}

如果我這樣做,這就是我所做的。我建議你試試這個方法。


查看完整回答
反對 回復 2021-09-29
  • 3 回答
  • 0 關注
  • 180 瀏覽
慕課專欄
更多

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號