以前操做Mysql數據庫都是使用客戶端工具登陸數據庫,而後再客戶端編寫SQL語句,發送到數據庫服務器執行,例如Mysql數據庫帶的mysql客戶端工具,能夠在命令行執行mysql -uUSERNAME -pPASSWORD
來登陸本機數據庫java
那麼在Java程序代碼中操做數據庫,可使用JDBC技術。mysql
JDBC(Java DataBase Connectivity,java數據庫鏈接)是一種用於執行SQL語句的Java API,能夠爲多種關係數據庫提供統一訪問,它由一組用Java語言編寫的類和接口組成。直白講就是使用Java代碼發送SQL語句的技術。sql
使用JDBC能夠鏈接不一樣的數據庫,只須要提供相應的驅動程序,驅動程序由數據庫廠商提供,就是一堆實現了JDBC接口的類。數據庫
這樣作的好處:api
鏈接數據庫咱們須要知道數據庫的地址,端口號,正確的用戶名和對應的密碼服務器
JDBC的核心接口和類位於Java標準庫的java.sql
和javax.sql
中,經常使用的主要位於java.sql中工具
核心類或者接口介紹:url
在註冊驅動以前,須要下載mysql數據庫的驅動程序jar包添加到項目中命令行
//1.建立數據庫驅動對象 Driver driver = new com.mysql.jdbc.Driver(); Properties info = new Properties(); info.setProperty("user", "root"); info.setProperty("password", "root"); //2. 鏈接數據庫 Connection connection = driver.connect(url, info);
//1.建立一個驅動對象 Driver driver = new com.mysql.jdbc.Driver();//這句代碼中已經註冊了驅動 // Driver driver2 = new com.orace.jdbc.Driver(); //2.註冊驅動程序(能夠註冊多個) DriverManager.registerDriver(driver); // DriverManager.registerDriver(driver2); //3. 獲取鏈接對象 Connection connection = DriverManager.getConnection(url, user, password);
上面使用DriverManager來註冊的方式實際會註冊兩次驅動3d
Class.forName("com.mysql.jdbc.Driver"); Connection connection = DriverManager.getConnection(url,user,password); System.out.println(connection);
推薦使用第三種方式
下面用一個實例展現JDBC技術發送SQL語句的通常步驟
事先已經在本地mysql服務器上建立了一個mydb的數據庫
/* * 執行DML(數據庫操縱語言)(insert update delete) * */ public class Demo2 { private String url="jdbc:mysql://localhost:3306/mydb"; private String user="root"; private String password="root"; @Test public void testInsert(){ Connection connection = null; Statement statement = null; try { Class.forName("com.mysql.jdbc.Driver"); connection = DriverManager.getConnection(url,user,password); statement = connection.createStatement(); String sql = "insert into student(name,gender) values('云溪','女')"; int count = statement.executeUpdate(sql); System.out.println("插入影響了"+count+"行"); } catch (ClassNotFoundException e) { e.printStackTrace(); throw new RuntimeException(e); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); }finally { if(statement!=null){ try { statement.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } if(connection!=null){ try { connection.close(); } catch (SQLException e) { e.printStackTrace(); throw new RuntimeException(e); } } } }