1. 程式人生 > 其它 >Jdbc實現Mysql連線

Jdbc實現Mysql連線

技術標籤:javamysqljdbc

第一步:匯入jar包
https://mvnrepository.com/
進入maven下載相應的jar包版本。直接在搜尋框裡搜尋mysql
在這裡插入圖片描述
進去版本都羅列出來了,你的mysql什麼版本就下載相應的大版本,
詳細的可以看下載數量,下載數量越多說明越穩定。
這裡我下載的5.1.38。

匯入Idea你的專案裡。
第二步:載入驅動
Class.forName(“com.mysql.jdbc.Driver”);
該方法利用反射。
官方推薦8.0以上用:com.mysql.cj.jdbc.Driver,就算你寫的上面的路徑,它也會給你轉成這樣的。

第三步:連線資料庫

DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?characterEncoding=utf8","root","root");

getConnection 方法有三個過載的方法,這裡只講一個。
第一個引數Url:
jdbc:是jdbc的協議
mysql:是mysql的協議
localhost:是主機地址
3306是埠號
db1是資料庫名稱
?後面的可選,如果新增資料出現亂碼說明應該修改字符集。

第二個引數是mysql使用者名稱
第三個引數是mysql密碼

這個方法會返回一個Connection物件

第四步:執行sql語句
從Connection 物件的方法createStatement()返回一個Statement物件。
Statement物件執行sql語句需要一個sql語句的字串。
如果你寫的sql語句是 dml(增刪改) ddl(操作資料庫和表)那你可以使用executeUpdate(sql),如果是查詢語句,你可以使用executeQuery(sql);

如果使用的查詢語句,那麼一定有會有結果resultSet
next()可以檢測是否有下一行

比較完整的例項程式碼

public class JDemo3 {
   private Connection connection=null;
private Statement statement=null; private ResultSet resultSet=null; private ArrayList<Emp> emps; @Before public void init(){ try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/db1?characterEncoding=utf8","root","root"); } catch (Exception e) { e.printStackTrace(); } } @Test public void test(){ try { statement = connection.createStatement(); String sql = "select * from emp"; resultSet = statement.executeQuery(sql); emps = new ArrayList(); while(resultSet.next()){ int uid= resultSet.getInt(1); String name = resultSet.getString(2); String gender = resultSet.getString(3); double salary = resultSet.getDouble(4); Date date = resultSet.getDate(5); int dept_id = resultSet.getInt(6); Emp emp = new Emp(uid, name, gender, salary, date, dept_id); emps.add(emp); } System.out.println(emps); } catch (Exception e) { e.printStackTrace(); }finally { /* if(resultSet!=null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement!=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } }*/ } } @After public void release(){ if(resultSet!=null){ try { resultSet.close(); } catch (SQLException e) { e.printStackTrace(); } } if(connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); } } if(statement!=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); } } } }