1. 程式人生 > >JDBC學習筆記 idea連線MySQL

JDBC學習筆記 idea連線MySQL

www.mysql.com->Products->DOWNLOADS->MySQL Connectors->Connector/J->選擇合適的版本->download
注.tar是Linux系統用的,windows 下載第二個(.zip)
連結地址:
https://dev.mysql.com/get/Downloads/Connector-J/mysql-connector-java-5.1.47.zip
下載之後解壓縮
開啟idea點選File選中Project Structure
在這裡插入圖片描述
Modules->Dependencies->"+"->“1.JARs or directories”
在這裡插入圖片描述


匯入合適的jar包即可。匯入成功後左側會出現依賴關係
在這裡插入圖片描述
寫如下程式碼,若執行成功則說明連線成功!(打驅動)
import java.sql.*;

 try {
       Class.forName("com.mysql.jdbc.Driver").newInstance();
     }catch (Exception e ){
       e.printStackTrace();
     }

連線好了我們就能查詢了

import java.io.FileNotFoundException;
import java.sql.*;

public class Main {
    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection("jdbc:mysql://localhost/mydata?user=root&password=root");
            stmt = conn.createStatement();
            rs = stmt.executeQuery("select * from dept");
            while (rs.next()) {
                System.out.println(rs.getString("deptno"));
            }
        } catch (SQLException e) {
            e.getSQLState();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } finally {
            try {
                if (conn != null)
                    conn.close();
                conn = null;
                if (stmt != null)
                    stmt.cancel();
                stmt = null;
                if (rs != null)
                    rs.close();
                rs = null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
}