java基于jdbc連接mysql數(shù)據(jù)庫功能實(shí)例詳解
本文實(shí)例講述了java基于jdbc連接mysql數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:
一、JDBC簡介
Java 數(shù)據(jù)庫連接,(Java Database Connectivity,簡稱JDBC)是Java語言中用來規(guī)范客戶端程序如何來訪問數(shù)據(jù)庫的應(yīng)用程序接口,提供了諸如查詢和更新數(shù)據(jù)庫中數(shù)據(jù)的方法。JDBC也是Sun Microsystems的商標(biāo)。它JDBC是面向關(guān)系型數(shù)據(jù)庫的。
1、JDBC架構(gòu):
JDBC API支持兩層和三層處理模型進(jìn)行數(shù)據(jù)庫訪問,但在一般的JDBC體系結(jié)構(gòu)由兩層組成:
JDBC API: 提供了應(yīng)用程序?qū)DBC的管理連接;
JDBC Driver API: 支持JDBC管理到驅(qū)動(dòng)器連接;
JDBC API的使用驅(qū)動(dòng)程序管理器和數(shù)據(jù)庫特定的驅(qū)動(dòng)程序提供透明的連接到異構(gòu)數(shù)據(jù)庫;
JDBC驅(qū)動(dòng)程序管理器可確保正確的驅(qū)動(dòng)程序來訪問每個(gè)數(shù)據(jù)源,該驅(qū)動(dòng)程序管理器能夠支持連接到多個(gè)異構(gòu)數(shù)據(jù)庫的多個(gè)并發(fā)的驅(qū)動(dòng)程序;
以下是結(jié)構(gòu)圖,它顯示了驅(qū)動(dòng)程序管理器方面的JDBC驅(qū)動(dòng)程序和Java應(yīng)用程序的位置:

2、常見的JDBC組件:
JDBC API提供了以下接口和類:
DriverManager: 這個(gè)類管理數(shù)據(jù)庫驅(qū)動(dòng)程序的列表,內(nèi)容是否符合從Java應(yīng)用程序使用的通信子協(xié)議正確的數(shù)據(jù)庫驅(qū)動(dòng)程序的連接請(qǐng)求,識(shí)別JDBC在一定子協(xié)議的第一個(gè)驅(qū)動(dòng)器將被用來建立數(shù)據(jù)庫連接;
Driver: 此接口處理與數(shù)據(jù)庫服務(wù)器通信,很少直接與驅(qū)動(dòng)程序?qū)ο?,相反,使用DriverManager中的對(duì)象,它管理此類型的對(duì)象,它也抽象與驅(qū)動(dòng)程序?qū)ο蠊ぷ飨嚓P(guān)的詳細(xì)信息;
Connection : 此接口與接觸數(shù)據(jù)庫的所有方法,連接對(duì)象表示通信上下文,即,與數(shù)據(jù)庫中的所有的通信是通過唯一的連接對(duì)象;
Statement : 可以使用這個(gè)接口創(chuàng)建的對(duì)象的SQL語句提交到數(shù)據(jù)庫,一些派生的接口接受除執(zhí)行存儲(chǔ)過程的參數(shù);
ResultSet: 這些對(duì)象保存從數(shù)據(jù)庫后,執(zhí)行使用Statement對(duì)象的SQL查詢中檢索數(shù)據(jù),它作為一個(gè)迭代器,讓您可以通過移動(dòng)它的數(shù)據(jù);
SQLException: 這個(gè)類處理發(fā)生在一個(gè)數(shù)據(jù)庫應(yīng)用程序的任何錯(cuò)誤.
二、連接JDBC需要掌握的基本知識(shí)
1、數(shù)據(jù)庫的基本操作,
eg:Mysql的安裝和基本操作(insert,delete,update,query)
2、java開發(fā)工具的使用,
eg:Eclipse/MyEclipse (包括mysql-connector-java-5.0.3-bin.jar的導(dǎo)入)
三、JDBC的連接及代碼演示
1、JDBC連接工具類
1)、Configuration.java:可以從.xml文件中連接數(shù)據(jù)庫的配置信息,需要引入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ù)庫的配置信息
<?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ù)庫表user中的id和name的bean類,其中id是自動(dò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連接的測試類
1)、TestJdbc.java:數(shù)據(jù)庫測試類
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ì)象:通過Connection對(duì)象傳入SQL查詢命令獲??;
3、獲取ResultSet:對(duì)PreparedStatement執(zhí)行executeUpdate()或者executeQurey()獲??;
4、依次關(guān)閉打開的對(duì)象:先后關(guān)閉ResultSet、PreparedStatement和Connection對(duì)象.
更多關(guān)于java相關(guān)內(nèi)容感興趣的讀者可查看本站專題:《Java+MySQL數(shù)據(jù)庫程序設(shè)計(jì)總結(jié)》、《Java數(shù)據(jù)結(jié)構(gòu)與算法教程》、《Java文件與目錄操作技巧匯總》、《Java操作DOM節(jié)點(diǎn)技巧總結(jié)》和《Java緩存操作技巧匯總》
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
相關(guān)文章
SpringBoot使用JavaMailSender實(shí)現(xiàn)發(fā)送郵件
JavaMailSender是Spring Framework中的一個(gè)接口,用于發(fā)送電子郵件,本文主要為大家詳細(xì)介紹了SpringBoot如何使用JavaMailSender實(shí)現(xiàn)發(fā)送郵件,需要的可以參考下2023-12-12
mybatis的映射xml中動(dòng)態(tài)設(shè)置orderby方式
這篇文章主要介紹了mybatis的映射xml中動(dòng)態(tài)設(shè)置orderby方式,具有很好的參考價(jià)值,希望對(duì)大家有所幫助。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2021-11-11
在Java的Hibernate框架中對(duì)數(shù)據(jù)庫數(shù)據(jù)進(jìn)行查詢操作
這篇文章主要介紹了Java的Hibernate框架中對(duì)數(shù)據(jù)庫數(shù)據(jù)進(jìn)行查詢操作的方法,Hibernate是Java的SSH三大web開發(fā)框架之一,需要的朋友可以參考下2015-12-12
SpringBoot中屬性賦值操作的實(shí)現(xiàn)
這篇文章主要介紹了SpringBoot中屬性賦值操作的實(shí)現(xiàn),文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-10-10
Java中的權(quán)重算法(如Dubbo的負(fù)載均衡權(quán)重)詳解
這篇文章主要介紹了Java中的權(quán)重算法(如Dubbo的負(fù)載均衡權(quán)重)詳解,負(fù)載均衡,其含義就是指將負(fù)載進(jìn)行平衡、分?jǐn)偟蕉鄠€(gè)操作單元上進(jìn)行運(yùn)行,例如FTP服務(wù)器、Web服務(wù)器、企業(yè)核心應(yīng)用服務(wù)器和其它主要任務(wù)服務(wù)器等,從而協(xié)同完成工作任務(wù),需要的朋友可以參考下2023-08-08
基于java實(shí)現(xiàn)租車管理系統(tǒng)
這篇文章主要為大家詳細(xì)介紹了基于java實(shí)現(xiàn)租車管理系統(tǒng),文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2020-12-12
mybatis plus動(dòng)態(tài)數(shù)據(jù)源切換及查詢過程淺析
這篇文章主要介紹了mybatis plus動(dòng)態(tài)數(shù)據(jù)源切換及查詢過程淺析,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2020-12-12

