java基于jdbc連接mysql數(shù)據(jù)庫(kù)功能實(shí)例詳解
本文實(shí)例講述了java基于jdbc連接mysql數(shù)據(jù)庫(kù)的方法。分享給大家供大家參考,具體如下:
一、JDBC簡(jiǎn)介
Java 數(shù)據(jù)庫(kù)連接,(Java Database Connectivity,簡(jiǎn)稱JDBC)是Java語(yǔ)言中用來(lái)規(guī)范客戶端程序如何來(lái)訪問(wèn)數(shù)據(jù)庫(kù)的應(yīng)用程序接口,提供了諸如查詢和更新數(shù)據(jù)庫(kù)中數(shù)據(jù)的方法。JDBC也是Sun Microsystems的商標(biāo)。它JDBC是面向關(guān)系型數(shù)據(jù)庫(kù)的。
1、JDBC架構(gòu):
JDBC API支持兩層和三層處理模型進(jìn)行數(shù)據(jù)庫(kù)訪問(wèn),但在一般的JDBC體系結(jié)構(gòu)由兩層組成:
JDBC API: 提供了應(yīng)用程序?qū)DBC的管理連接;
JDBC Driver API: 支持JDBC管理到驅(qū)動(dòng)器連接;
JDBC API的使用驅(qū)動(dòng)程序管理器和數(shù)據(jù)庫(kù)特定的驅(qū)動(dòng)程序提供透明的連接到異構(gòu)數(shù)據(jù)庫(kù);
JDBC驅(qū)動(dòng)程序管理器可確保正確的驅(qū)動(dòng)程序來(lái)訪問(wèn)每個(gè)數(shù)據(jù)源,該驅(qū)動(dòng)程序管理器能夠支持連接到多個(gè)異構(gòu)數(shù)據(jù)庫(kù)的多個(gè)并發(fā)的驅(qū)動(dòng)程序;
以下是結(jié)構(gòu)圖,它顯示了驅(qū)動(dòng)程序管理器方面的JDBC驅(qū)動(dòng)程序和Java應(yīng)用程序的位置:
2、常見(jiàn)的JDBC組件:
JDBC API提供了以下接口和類:
DriverManager: 這個(gè)類管理數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序的列表,內(nèi)容是否符合從Java應(yīng)用程序使用的通信子協(xié)議正確的數(shù)據(jù)庫(kù)驅(qū)動(dòng)程序的連接請(qǐng)求,識(shí)別JDBC在一定子協(xié)議的第一個(gè)驅(qū)動(dòng)器將被用來(lái)建立數(shù)據(jù)庫(kù)連接;
Driver: 此接口處理與數(shù)據(jù)庫(kù)服務(wù)器通信,很少直接與驅(qū)動(dòng)程序?qū)ο?,相反,使用DriverManager中的對(duì)象,它管理此類型的對(duì)象,它也抽象與驅(qū)動(dòng)程序?qū)ο蠊ぷ飨嚓P(guān)的詳細(xì)信息;
Connection : 此接口與接觸數(shù)據(jù)庫(kù)的所有方法,連接對(duì)象表示通信上下文,即,與數(shù)據(jù)庫(kù)中的所有的通信是通過(guò)唯一的連接對(duì)象;
Statement : 可以使用這個(gè)接口創(chuàng)建的對(duì)象的SQL語(yǔ)句提交到數(shù)據(jù)庫(kù),一些派生的接口接受除執(zhí)行存儲(chǔ)過(guò)程的參數(shù);
ResultSet: 這些對(duì)象保存從數(shù)據(jù)庫(kù)后,執(zhí)行使用Statement對(duì)象的SQL查詢中檢索數(shù)據(jù),它作為一個(gè)迭代器,讓您可以通過(guò)移動(dòng)它的數(shù)據(jù);
SQLException: 這個(gè)類處理發(fā)生在一個(gè)數(shù)據(jù)庫(kù)應(yīng)用程序的任何錯(cuò)誤.
二、連接JDBC需要掌握的基本知識(shí)
1、數(shù)據(jù)庫(kù)的基本操作,
eg:Mysql的安裝和基本操作(insert,delete,update,query)
2、java開(kāi)發(fā)工具的使用,
eg:Eclipse/MyEclipse (包括mysql-connector-java-5.0.3-bin.jar的導(dǎo)入)
三、JDBC的連接及代碼演示
1、JDBC連接工具類
1)、Configuration.java:可以從.xml文件中連接數(shù)據(jù)庫(kù)的配置信息,需要引入dom4j-1.6.1.jar包
package cn.java.jdbc; import java.io.InputStream; import org.dom4j.Document; import org.dom4j.DocumentException; import org.dom4j.Element; import org.dom4j.io.SAXReader; public class Configuration { private String url; private String driver; private String username; private String password; public Configuration() { } public Configuration(String url, String driver, String username, String password) { super(); this.url = url; this.driver = driver; this.username = username; this.password = password; } public static Configuration getConfigure() { try { InputStream in = Configuration.class.getResourceAsStream("/db.xml"); if (null!=in) { return load(in); } return null; } catch (DocumentException e) { e.printStackTrace(); return null; } } private static Configuration load(InputStream in) throws DocumentException { SAXReader reader = new SAXReader(); Document doc = reader.read(in); Element jdbc = doc.getRootElement(); String url = jdbc.element("url").getText(); String driver = jdbc.element("driver").getText(); String username = jdbc.element("username").getText(); String password = jdbc.element("password").getText(); Configuration cfg = new Configuration(url, driver, username, password); return cfg; } public String getUrl() { return url; } public void setUrl(String url) { this.url = url; } public String getDriver() { return driver; } public void setDriver(String driver) { this.driver = driver; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } }
2)、db.xml:保存數(shù)據(jù)庫(kù)的配置信息
<?xml version="1.0" encoding="UTF-8"?> <jdbc> <url>jdbc:mysql://localhost:3306/test</url> <driver>com.mysql.jdbc.Driver</driver> <username>root</username> <password></password> </jdbc>
3)、ConnectionFactory.java:JDBC連接工廠方法之一
package cn.java.jdbc; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class ConnectionFactory { private static ConnectionFactory connectionFactory=null; private static Configuration config=Configuration.getConfigure(); private ConnectionFactory() { try { Class.forName(config.getDriver()); } catch (ClassNotFoundException e) { } } public Connection getConnection() throws SQLException { Connection con=null; try { con=DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword()); return con; }finally{ // if (null != con) { // con.close(); // } } } public static ConnectionFactory getInstance() { if (null==connectionFactory) { connectionFactory=new ConnectionFactory(); } return connectionFactory; } }
4)、ConnectionFactory2.java:JDBC連接工廠方法之二
package cn.java.jdbc; import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mysql.jdbc.jdbc2.optional.MysqlDataSource; public class ConnectionFactory2 { private DataSource ds ; private static ConnectionFactory2 connectionFactory2 = null; private ConnectionFactory2() { MysqlDataSource myDS = new MysqlDataSource() ; myDS.setServerName("localhost"); myDS.setDatabaseName("test"); myDS.setPort(3306) ; myDS.setUser("root"); myDS.setCharacterEncoding("utf-8"); myDS.setPassword(""); this.ds = myDS ; } public Connection getConnection() throws SQLException { Connection conn = null; try { conn = ds.getConnection() ; conn.setAutoCommit(false); return conn; } catch (SQLException e) { if (null != conn) { conn.close(); } throw e; } } public static ConnectionFactory2 getInstance() { if (null == connectionFactory2) { connectionFactory2 = new ConnectionFactory2(); } return connectionFactory2; } }
5)、User.java:定義數(shù)據(jù)庫(kù)表user中的id和name的bean類,其中id是自動(dòng)增長(zhǎng)的
package cn.java.jdbc; public class User { private int id; private String name; public User() { } public User(int id, String name) { this.id = id; this.name = name; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
6)、UserDao.java:user表的操作類,實(shí)現(xiàn)了insert、delete、update、query等方法
package cn.java.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.ArrayList; import java.util.List; public class UserDao { private PreparedStatement st = null; private ResultSet rs = null; public UserDao() { } public void insert( Connection con,String name) throws SQLException,IOException { String sql="insert into user(name) values(?) "; try{ st=con.prepareStatement(sql); st.setString(1, name); st.executeUpdate(); }finally{ if (null!=st) { st.close(); } } } public void delete(Connection con,int id) throws SQLException,IOException { String sql="delete from user where id=?"; try{ st=con.prepareStatement(sql); st.setInt(1, id); st.executeUpdate(); }finally{ if (null!=st) { st.close(); } } } public void update( Connection con,int id,String name) throws SQLException,IOException { String sql="update user set name=? where id=?"; try{ st=con.prepareStatement(sql); st.setString(1, name); st.setInt(2, id); st.executeUpdate(); }finally{ if (null!=st) { st.close(); } } } public User query(Connection con,int index) throws SQLException,IOException{ User user=new User(); String sql="select * from user where id=?"; try{ st=con.prepareStatement(sql); st.setInt(1, index); rs=st.executeQuery(); while (rs.next()) { user.setId(rs.getInt(1)); user.setName(rs.getString(2)); break; } }finally{ if (null!=rs) { rs.close(); } if (null!=st) { st.close(); } } return user; } public List<User> queryAll(Connection con) throws SQLException,IOException { List<User> list=new ArrayList<>(); String sql="select * from user"; try { st=con.prepareStatement(sql); rs=st.executeQuery(); while (rs.next()) { User user=new User(); user.setId(rs.getInt(1)); user.setName(rs.getString(2)); list.add(user); } }finally{ if (null!=rs) { rs.close(); } if (null!=st) { st.close(); } } return list; } }
2、JDBC連接的測(cè)試類
1)、TestJdbc.java:數(shù)據(jù)庫(kù)測(cè)試類
package cn.java.jdbc; import java.io.IOException; import java.sql.Connection; import java.sql.SQLException; import java.util.List; public class TestJdbc { public static void main(String[] args) { Connection con=null; try { con=(Connection) ConnectionFactory.getInstance().getConnection(); UserDao userDao=new UserDao(); //con=(Connection) ConnectionFactory2.getInstance().getConnection(); if (null!=con) { System.out.println("Link JDBC SUCESS"); //userDao.insert(con, "zhangsir"); //userDao.delete(con, 4); //userDao.update(con, 1, "david"); List<User> list=userDao.queryAll(con); for (User user : list) { System.out.println("id="+user.getId()+" name="+user.getName()); } } } catch (SQLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); }finally{ if (null!=con) { try { con.close(); } catch (SQLException e) { } } } } }
三、JDBC連接總結(jié)
JDBC操作的基本步驟是:
1、創(chuàng)建Connection對(duì)象,傳入SQL查詢命令字符串;
2、獲取PreparedStatement對(duì)象:通過(guò)Connection對(duì)象傳入SQL查詢命令獲?。?br />
3、獲取ResultSet:對(duì)PreparedStatement執(zhí)行executeUpdate()
或者executeQurey()
獲取;
4、依次關(guān)閉打開(kāi)的對(duì)象:先后關(guān)閉ResultSet、PreparedStatement和Connection對(duì)象.
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java+MySQL數(shù)據(jù)庫(kù)程序設(shè)計(jì)總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java文件與目錄操作技巧匯總》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章
Spring Boot項(xiàng)目利用Redis實(shí)現(xiàn)session管理實(shí)例
本篇文章主要介紹了Spring Boot項(xiàng)目利用Redis實(shí)現(xiàn)session管理實(shí)例,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2017-06-06詳解利用SpringMVC攔截器控制Controller返回值
這篇文章主要介紹了詳解利用SpringMVC攔截器控制Controller返回值,通過(guò)定義一個(gè)StringResult注解,在訪問(wèn)方法的時(shí)候返回StringResult中的內(nèi)容,有興趣的可以了解一下。2017-01-01Spring Cloud Gateway 獲取請(qǐng)求體(Request Body)的多種方法
這篇文章主要介紹了Spring Cloud Gateway 獲取請(qǐng)求體(Request Body)的多種方法,本文通過(guò)實(shí)例代碼給大家介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或工作具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2021-01-01SpringSecurity學(xué)習(xí)之自定義過(guò)濾器的實(shí)現(xiàn)代碼
這篇文章主要介紹了SpringSecurity學(xué)習(xí)之自定義過(guò)濾器的實(shí)現(xiàn)代碼,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2019-01-01mybatis-plus(insertBatchSomeColumn批量添加方式)
這篇文章主要介紹了mybatis-plus(insertBatchSomeColumn批量添加方式),具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-03-03fastjson全局日期序列化設(shè)置導(dǎo)致JSONField失效問(wèn)題解決方案
這篇文章主要介紹了fastjson通過(guò)代碼指定全局序列化返回時(shí)間格式,導(dǎo)致使用JSONField注解標(biāo)注屬性的特殊日期返回格式失效問(wèn)題的解決方案2023-01-01基于SpringBoot+Avue實(shí)現(xiàn)短信通知功能
Avue是基于vue和element-ui的快速開(kāi)發(fā)框架 ,它的核心是數(shù)據(jù)驅(qū)動(dòng)UI的思想,讓我們從繁瑣的crud開(kāi)發(fā)中解脫出來(lái),本文將給大家介紹一下使用SpringBoot+Avue實(shí)現(xiàn)短信通知功能,文中有詳細(xì)的代碼示例,需要的朋友可以參考下2023-09-09java equals和=,==的區(qū)別詳細(xì)介紹
這篇文章主要介紹了java equals和=,==的區(qū)別,學(xué)習(xí)Java的朋友對(duì)equals 和== 這個(gè)概念開(kāi)始使用的時(shí)候會(huì)有疑問(wèn),很難辨別如何正確使用,這里幫大家詳細(xì)講解該知識(shí)點(diǎn),希望大家能掌握,有需要的小伙伴可以參考下2016-10-10spring boot整合jsp及設(shè)置啟動(dòng)頁(yè)面的方法
這篇文章主要給大家介紹了關(guān)于spring boot整合jsp及設(shè)置啟動(dòng)頁(yè)面的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2018-09-09