學習筆記 | JAVA調(diào)用MySQL數(shù)據(jù)庫

最近可能需要用到用java調(diào)用MySQL數(shù)據(jù)庫,java提供了接口,打算趕緊學來用用!

軟件使用:Eclipse。

下載

java連接MySQL需要驅動包,所以需要下載jar包。網(wǎng)上各處都有提供.

一般長這樣

mysql-connector-java-5.1.38.jar

配置

1.新建一個項目,在自己的項目新建一個文件夾(用來存儲jar包)

將自己下載的jar包直接拖入這個文件夾就行了。

2.接下來在項目下右鍵選擇Configure Build Path

image

3.選擇Libraries下的Add JARS...找到下載的jar包,完成!

image

使用

首先import sql包

import java.sql.*;

在自己本身MySQL有一個數(shù)據(jù)庫后

image

我們創(chuàng)建一些初始數(shù)據(jù)

/*
MySQL的JDBC URL編寫方式:
jdbc:mysql://主機名稱:連接端口/數(shù)據(jù)庫名稱?參數(shù)=值
為了避免中文亂碼要設置"characterEncoding=utf8"
*/

//創(chuàng)建數(shù)據(jù)庫URL
static final String DB_URL = "jdbc:mysql://localhost:3306/test?characterEncoding=utf8&useSSL=true";

// 數(shù)據(jù)庫的用戶名與密碼,需要根據(jù)自己的設置
static final String USER = "root";
static final String PASS = "root";

創(chuàng)建完,在主函數(shù)加載驅動程序及使用

public static void main(String[] args) {
    Connection con = null;
//1. 注冊 JDBC 驅動
    Class.forName("com.mysql.jdbc.Driver");
    System.out.println("成功加載MySQL驅動");
//2. 獲得數(shù)據(jù)庫連接
    System.out.println("連接數(shù)據(jù)庫...");
    Connection conn = DriverManager.getConnection(DB_URL,USER,PASS);
    System.out.println("成功連接數(shù)據(jù)庫");
//3. 成功即可操作數(shù)據(jù)庫,創(chuàng)建Statenment實例
    Statement stmt = conn.createStatement();
    // Statement里面帶有很多方法,比如executeUpdate可以實現(xiàn)插入,更新和刪除等
    ResultSet rs = stmt.executeQuery("SELECT * FROM websites");
//4. 如果有數(shù)據(jù),rs.next()返回true
    while(rs.next()){
        System.out.println(" 名稱:"+rs.getString("name")+" 地址:"+rs.getString("url"));
    }
}

最簡單就是上面四個步驟,我分別解釋了上面意思。

其實還需要有處理各種錯誤的情況,還有斷開連接的函數(shù)。

讓我們看看結果呈現(xiàn)上面吧

image

可見已經(jīng)成功連接數(shù)據(jù)庫,并且用sql語句調(diào)用數(shù)據(jù)庫。

創(chuàng)建數(shù)據(jù)表并插入數(shù)據(jù)

 public static void main(String[] args) {
        Connection conn=null;
        Statement  stmt=null;
    try {
        //1.加載驅動程序
        Class.forName("com.mysql.jdbc.Driver");
        
        //2. 獲得數(shù)據(jù)庫連接
        System.out.println("連接數(shù)據(jù)庫...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        
        //3.操作數(shù)據(jù)庫,實現(xiàn)增刪改查
        stmt = conn.createStatement();
        String mysql;
        mysql="create table student(NO char(20),name varchar(20),primary key(NO))";
        //創(chuàng)建表格
        
        int result=stmt.executeUpdate(mysql);
        //在執(zhí)行之后,查看受影響行數(shù),返回-1代表不成功
        
        if(result!=-1) {
            System.out.println("創(chuàng)建students表格成功");
            mysql = "insert into student(NO,name) values('2016001','haige')";
            result= stmt.executeUpdate(mysql);
            mysql = "insert into student(NO,name) values('2016002','Mr.chen')";
            result= stmt.executeUpdate(mysql);
            System.out.println("插入完成");
            
            mysql = "select * from student";
            ResultSet rs = stmt.executeQuery(mysql);
            //執(zhí)行查詢語句看結果
            
            System.out.println("學號\t姓名");
            while(rs.next()){
                String student_id=rs.getString(1);
                String student_name =rs.getString(2);
                System.out.println(student_id+"\t"+student_name);
            }
            rs.close();
            stmt.close();
            conn.close();
        }
      }catch (SQLException e) {
          System.out.println("MySQL操作錯誤");
          e.printStackTrace();
      } catch (Exception e) {
          e.printStackTrace();
      }
      System.out.println("程序結束!");
  }

以上我加入了try-catch是為了在錯誤時可以檢測出錯誤的地方,可以不加。

還加入了close關閉數(shù)據(jù)庫的連接的操作。

image

更新刪除操作

//SQL語句
update student set name=? where NO='2016002'

現(xiàn)在對數(shù)據(jù)庫進行更新刪除操作

public static void main(String[] args) {
        Connection conn=null;
        Statement  stmt=null;
    try {
        //1.加載驅動程序
        Class.forName("com.mysql.jdbc.Driver");
        
        //2. 獲得數(shù)據(jù)庫連接
        System.out.println("連接數(shù)據(jù)庫...");
        conn = DriverManager.getConnection(DB_URL, USER, PASS);
        
        //3.操作數(shù)據(jù)庫,實現(xiàn)增刪改查
        stmt = conn.createStatement();
        String mysql,mysql2,mysql3;
        
        //更新操作
        mysql="update student set name=? where NO='2016002'";
        PreparedStatement pst=conn.prepareStatement(mysql);
        pst.setString(1, "chenxx");
        pst.executeUpdate();
        System.out.println("更新為chenxx完成");
        
        //刪除操作
        mysql2="delete from student where name=?";
        pst = conn.prepareStatement(mysql2);
        pst.setString(1, "haige");
        pst.executeUpdate();
        System.out.println("刪除haige完成");
        
        //查詢操作
        mysql3="select * from student";
        ResultSet rs = stmt.executeQuery(mysql3);
        System.out.println("查詢完成");
        
        //執(zhí)行查詢語句看結果
        System.out.println("學號\t姓名");
        while(rs.next()){
            String student_id=rs.getString(1);
            String student_name =rs.getString(2);
            System.out.println(student_id+"\t"+student_name);
        }
        rs.close();
        stmt.close();
        conn.close();
            
      }catch (SQLException e) {
          System.out.println("MySQL操作錯誤");
          e.printStackTrace();
      }catch (Exception e) {
          e.printStackTrace();
      }
      System.out.println("程序結束!");
  }
image

很好,結果如我們所料!

現(xiàn)在暫時沒啥問題,目前還只是基礎,等到真正使用起來可能會有一些問題,到時候再記錄下來吧!

-to be continue-

學習筆記

?著作權歸作者所有,轉載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

相關閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容