本文實(shí)例講述了java基于jdbc連接mysql數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:
一、JDBC簡(jiǎn)介
Java 數(shù)據(jù)庫連接,(Java Database Connectivity,簡(jiǎn)稱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ū)ο螅喾矗褂肈riverManager中的對(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包
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
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ù)庫的配置信息
1
2
3
4
5
6
7
|
<? 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連接工廠方法之一
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
|
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連接工廠方法之二
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
|
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)增長(zhǎng)的
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
|
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等方法
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
|
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ù)庫測(cè)試類
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
|
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ì)象.
希望本文所述對(duì)大家java程序設(shè)計(jì)有所幫助。
原文鏈接:http://blog.csdn.net/j086924/article/details/51546876