日期:2014-05-16  浏览次数:20478 次

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

用的MYSQL的驱动链接

package com.sg.test;

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

public class Base {
?public static void main(String[] args) {
??try {
???Base.test01();
??} catch (Exception e) {
???e.printStackTrace();
??}
?}

?static void test01() throws Exception {
??// 注册驱动

? //第一种
??DriverManager.registerDriver(new com.mysql.jdbc.Driver());

? //第二种

?? System.setProperty("jdbc:drivers", "com.mysql.jdbc.Driver");

??//第三种? (推荐使用)

? Class.forName("com.mysql.jdbc.Driver");
??// 建立连接
??java.sql.Connection conn = DriverManager.getConnection(
????"jdbc:mysql://localhost:3306/jdbc", "root", "root");
??// 创建语句
??Statement st = conn.createStatement();
??// 执行语句
??ResultSet rs = st.executeQuery("select * from user");
??// 处理结果
??while (rs.next()) {
???System.out.println("id:" + rs.getInt(1) + "\n name:"
?????+ 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/jd