您的位置:首页 > 其它

JDBC 使用总结

2016-05-02 00:00 351 查看
摘要: JDBC 如何连接 数据库 ,DAO 应用

JDBC

简介 : 数据存储于数据库中,应用程序的使用需要访问数据库 ,各个数据库厂商不同 ,数据库 访问方式不同 ,因此 JAVA 开发提供一套标准的API 借口 用来解决应用程序访问数据库的问题 ,JDBC 是 应用程序访问数据库的解决方案 ,虽然JDBC 在一定程度上影响了访问数据库的速度,并且会导致 更改源数据较复杂,但是实现了跨平台,面向对象,通用性好。JDBC 可做三件事:与数据库建立连接、发送 操作数据库的语句并处理结果。

JDBC 连接数据库 步骤:

①加载驱动(数据库的实现类),

//使用CLASS下forName() 方法  oracle实现
Class.forName("oracle.jdbc.driver.OracleDriver") ;
// mysql 实现
Class.forName("com.mysql.jdbc.Driver");


②建立连接:

String url="jdbc:oracle:thin:@localhost:1521:boson1"; //oracle 实现
String url="com/tarena/dms/daodemo/v2/db.properties";//mysql 实现
String user="userid";//账号
String password="password"; //密码
Connection  conn= DriverManager.getConnection(url,user,password);


③创建语句对象

Statement st=conn.createStatement();


④执行SQL语句

String sql= "insert (name ,age ,hiredate) into emp values ('TOM',18,sysdate)";
ResultSet rs = st.executeQuery(sql); //结果集合
boolean rs1 =st.execute(); // 操作是否成功


⑤处理结果集

// 获取结果集
while(rs.next()){
String name =rs.getString ("name");
Integer age =   rs.getInt ("age");
Date date =rs.getDate("date");
System.out.println( name+""+age+""+hiredate);
}


⑥关闭连接

conn.close();// 需要处理异常


3.完整代码举例 :

例一:

创建配置文件db.properties保存 URL,USER ,PASSWORD ,CLASSNAME 等属性 。

# DB.properties 配置文件
jdbc.drive="oracle.jdbc.driver.OracleDriver"
jdbc.url="jdbc:oracle:thin:@localhost:1521:boson1";
jdbc.user="admin";
jdbc.password="password";


JAVA代码部分 -1 ,

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtility {
private static Properties properties =new Properties() ;
private static String driver = null;
private static String url = null;
private static String user = null;
private static String pwd = null;

static {
try {
// 加载配置文件
properties.load(DBUtility.class.getClassLoader().getResourceAsStream(
"db.properties"));
driver = properties.getProperty("jdbc.driver");
url = properties.getProperty("jdbc.url");
user = properties.getProperty("jdbc.user");
pwd = properties.getProperty("jdbc.password");
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
public static Connection openConnection() throws SQLException {
return DriverManager.getConnection(url, user, pwd);
}
public static void closeConnection(Connection con) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
System.out.println("关闭连接时发生异常");
}
}
}
}


DAO 类

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class EmpDAO {
public static void main(String[] args) {
EmpDAO dao = new EmpDAO();
dao.findAll();
}

public void findAll() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

try {
con = DBUtility.openConnection();
stmt = con.createStatement();
rs = stmt
.executeQuery("select empno, ename, sal, hiredate from emp");
while (rs.next()) {
System.out.println(rs.getInt("empno") + ","
+ rs.getString("ename") + "," + ","
+ rs.getDouble("sal") + "," + rs.getDate("hiredate"));
}
} catch (SQLException e) {
System.out.println("数据库访问异常!");
throw new RuntimeException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
} catch (SQLException e) {
System.out.println("释放资源时发生异常");
}
DBUtility.closeConnection(con);
}
}
}


直接使用JDBC访问数据库时,需要避免以下隐患:

1.每一次数据操作请求都需要建立数据库连接、打开连接、存取数据和关闭连接等步骤。而建立和打开数据库连接是一件既耗资源又费时的过程,如果频繁发生这种数据库操作,势必会使系统性能下降。

2. 连接对象代表着数据库系统的连接进程,是有限的资源。如果系统的使用用户非常多,有可能超出数据库服务器的承受极限,造成系统的崩溃。

数据库连接池是解决上述问题最常用的方法。所谓连接池,即可以创建并持有数据库连接的组件。连接池可以预先创建并封装一些连接对象并将其缓存起来,当需要使用连接对象时可以向连接池“借”一个连接,用完之后将其“归还”到连接池中。数据库连接池的主要功能如下:

1. 连接池对象的创建和释放。

2. 服务器启动时,创建指定数量的数据库连接。

3. 为用户请求提供可用连接。如果没有空闲连接,且连接数没有超出最大值,创建一个新的数据库连接。

4. 将用户不再使用的连接标识为可用连接,等待其他用户请求。

5. 当空闲的连接数过多时,释放连接对象。

例二:(使用连接池)

配置文件内容:

jdbc.driverClassName=oracle.jdbc.OracleDriver
jdbc.url=jdbc:oracle:thin:@localhost:1521:orcl
jdbc.username=scott
jdbc.password=tiger

#<!-- 初始化连接 -->
dataSource.initialSize=10
#<!-- 最大空闲连接 -->
dataSource.maxIdle=20
#<!-- 最小空闲连接 -->
dataSource.minIdle=5
#最大连接数量
dataSource.maxActive=50
#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
dataSource.maxWait=1000


JAVA代码部分

DButil 类:

import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

import org.apache.commons.dbcp.BasicDataSource;

public class ConnectionSource {
private static BasicDataSource dataSource = null;

public ConnectionSource() {
}
public static void init() {

Properties dbProps = new Properties();
// 取配置文件可以根据实际的不同修改
try {
dbProps.load(ConnectionSource.class.getClassLoader().getResourceAsStream(
"day01/v4/db.properties"));
} catch (IOException e) {
e.printStackTrace();
}

try {
String driveClassName = dbProps.getProperty("jdbc.driverClassName");
String url = dbProps.getProperty("jdbc.url");
String username = dbProps.getProperty("jdbc.username");
String password = dbProps.getProperty("jdbc.password");

String initialSize = dbProps.getProperty("dataSource.initialSize");
String minIdle = dbProps.getProperty("dataSource.minIdle");
String maxIdle = dbProps.getProperty("dataSource.maxIdle");
String maxWait = dbProps.getProperty("dataSource.maxWait");
String maxActive = dbProps.getProperty("dataSource.maxActive");

dataSource = new BasicDataSource();
dataSource.setDriverClassName(driveClassName);
dataSource.setUrl(url);
dataSource.setUsername(username);
dataSource.setPassword(password);

// 初始化连接数
if (initialSize != null)
dataSource.setInitialSize(Integer.parseInt(initialSize));

// 最小空闲连接
if (minIdle != null)
dataSource.setMinIdle(Integer.parseInt(minIdle));

// 最大空闲连接
if (maxIdle != null)
dataSource.setMaxIdle(Integer.parseInt(maxIdle));

// 超时回收时间(以毫秒为单位)
if (maxWait != null)
dataSource.setMaxWait(Long.parseLong(maxWait));

// 最大连接数
if (maxActive != null) {
if (!maxActive.trim().equals("0"))
dataSource.setMaxActive(Integer.parseInt(maxActive));
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("创建连接池失败!请检查设置!!!");
}
}

public static synchronized Connection getConnection() throws SQLException {
if (dataSource == null) {
init();
}
Connection conn = null;
if (dataSource != null) {
conn = dataSource.getConnection();
}
return conn;
}
}


DAO类:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class EmpDAO {
public static void main(String[] args) {
EmpDAO dao = new EmpDAO();
dao.findAll();
}

public void findAll() {
Connection con = null;
Statement stmt = null;
ResultSet rs = null;

try {
con = ConnectionSource.getConnection();
stmt = con.createStatement();
rs = stmt
.executeQuery("select empno, ename, sal, hiredate from emp");
while (rs.next()) {
System.out.println(rs.getInt("empno") + ","
+ rs.getString("ename") + "," + ","
+ rs.getDouble("sal") + "," + rs.getDate("hiredate"));
}
} catch (SQLException e) {
System.out.println("数据库访问异常!");
throw new RuntimeException(e);
} finally {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException e) {
System.out.println("释放资源时发生异常");
}
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  JDBC DAO 连接池