首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > 其他数据库 >

JDBC学习一 基础一个简单JDBC几种不同连接驱动实现及简单的封装 单例模式 处理并发有关问题的封装 简单一个查询

2013-01-26 
JDBC学习一基础一个简单JDBC几种不同连接驱动实现及简单的封装 单例模式 处理并发问题的封装简单一个查询?

JDBC学习一 基础一个简单JDBC几种不同连接驱动实现及简单的封装 单例模式 处理并发问题的封装 简单一个查询
?????+ rs.getString(2) + "\n age:" + rs.getInt(3) + "\n sex"
?????+ rs.getString(4) + "\n brithday:" + rs.getDate(5));
??}
??//关闭资源
??rs.close();
??st.close();
??conn.close();
?}

}
封装一个jdbcUtil类

package com.sg.test;

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

public class jdbcUtil {
?static String url = "jdbc:mysql://localhost:3306/jdbc";
?static String username = "root";
?static String password = "root";

?static {
??try {
???Class.forName("com.mysql.jdbc.Driver");

??} catch (ClassNotFoundException e) {
???e.printStackTrace();
??}
?}

?public static Connection getConnection() throws SQLException {
??return DriverManager.getConnection(url, username, password);
?}

?public static void free(Statement st, Connection conn, ResultSet rs) {
??try {
???if (rs != null) {
????rs.close();
???}
??} catch (SQLException e) {
???e.printStackTrace();
??} finally {
???try {
????if (conn != null) {
?????conn.close();
????}
???} catch (SQLException e2) {
????e2.printStackTrace();
???} finally {
????try {
?????if (st != null) {
??????st.close();
?????}
????} catch (SQLException e2) {
?????e2.printStackTrace();
????}
???}
??}
?}
}

单例模式 考虑并发延迟

jdbcUtil02

public final class jdbcUtil02 {
?static String url = "jdbc:mysql://localhost:3306/jdbc";
?static String username = "root";
?static String password = "root";

?// private static jdbcUtil02 instance = new jdbcUtil02();
?private static jdbcUtil02 instance = null;

?// 构造私有化
?private jdbcUtil02() {

?}

?// 提供一个公共的static方法
?public static jdbcUtil02 getInstance() {

??// 延迟加载 使用的时候new
??// 处理并发问题 可以加锁
??synchronized (jdbcUtil02.class) {
???if (instance == null) {
????instance = new jdbcUtil02();
???}
??}
??return instance;
?}

?public Connection getConnection() throws SQLException {
??return DriverManager.getConnection(url, username, password);
?}
}

热点排行