web框架学习前复习——JDBC

JDBC编码步骤

public static void main(String[] args) throws SQLException {
         //注册驱动
     // DriverManager.registerDriver(new com.mysql.jdbc.Driver());这个也可
        Class.forName("com.mysql.jdbc.Driver");
        //获取与数据库的连接
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test","root","123456");
        //创建mysql执行对象   
        //Statement state = conn.createStatement();这个会有安全问题
        //执行sql语句
        //ResultSet rs = state.executeQuery("select * from USERS");
         PreparedStatement ps = conn.prepareStatement("select * from USERS");//建议使用这个会预编译sql语句。
        ResultSet rs = ps.executeQuery();
        //查询语句需要遍历结果
        while (rs.next()) {            
            System.out.println(rs.getObject("id"));
                //根据表的列来遍历
        }
        //关闭连接资源
        rs.close();
        state.close();
        conn.close();
    }

制作JDBCUtil工具类

//建立属性文件jdbc.properties
dirverclass=com.mysql.jdbc.Driver;
url=jdbc:mysql://localhost:3306/test;
user=root;
password=123456;
//建立工具类JdbcUtil
public class JdbcUtil {
    private static String driverClass;
    private static String url;
    private static String user;
    private static String password;
    static{
        try {
            ClassLoader cl = JdbcUtil.class.getClassLoader();
            InputStream in = cl.getResourceAsStream("jdbc.properties");
            Properties pr = new Properties();
            pr.load(in);
           driverClass=pr.getProperty("driverClass");
           url = pr.getProperty("url");
           user = pr.getProperty("user");
           password = pr.getProperty("password");
           Class.forName(driverClass);
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    public static Connection getConnection() throws SQLException{
        Connection conn = DriverManager.getConnection(url, user, password);
        return conn;
    }
    public static void reless(ResultSet rs,Statement state,Connection conn ){
        if (rs !=null) {
            try {
                rs.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            rs = null;
        }
        if(state!=null){
            try {
                state.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            state=null;
        }
        if(conn!=null){
            try {
                conn.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
            conn=null;
        }
    }
}

DBCP连接数据库

//拷贝jar包可网上下载开源组件
//编写dbcpconfig.properties属性文件
#连接设置
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root
password=123456

#<!-- 初始化连接 -->
initialSize=10

#最大连接数量
maxActive=50

#<!-- 最大空闲连接 -->
maxIdle=20

#<!-- 最小空闲连接 -->
minIdle=5

#<!-- 超时等待时间以毫秒为单位 6000毫秒/1000等于60秒 -->
maxWait=60000


#JDBC驱动建立连接时附带的连接属性属性的格式必须为这样:[属性名=property;] 
#注意:"user" 与 "password" 两个属性会被明确地传递,因此这里不需要包含他们。
connectionProperties=useUnicode=true;characterEncoding=utf8

#指定由连接池所创建的连接的自动提交(auto-commit)状态。
defaultAutoCommit=true

#driver default 指定由连接池所创建的连接的只读(read-only)状态。
#如果没有设置该值,则“setReadOnly”方法将不被调用。(某些驱动并不支持只读模式,如:Informix)
defaultReadOnly=

#driver default 指定由连接池所创建的连接的事务级别(TransactionIsolation)。
#可用值为下列之一:(详情可见javadoc。)NONE,READ_UNCOMMITTED, READ_COMMITTED, REPEATABLE_READ, SERIALIZABLE
defaultTransactionIsolation=REPEATABLE_READ


//编写DBCPUtil提供工具类
import java.io.InputStream;
import java.sql.Connection;
import java.util.Properties;
import javax.sql.DataSource;
import org.apache.commons.dbcp.BasicDataSourceFactory;



public class DbcpJdbc {
    private  static DataSource dataSource;
    static{
        try {
            InputStream in = DbcpJdbc.class.getResourceAsStream("dbcpconfig.properties");
            Properties prop = new Properties();
            prop.load(in);
            dataSource = BasicDataSourceFactory.createDataSource(prop);
        } catch (Exception e) {
            throw new ExceptionInInitializerError(e);
        }
    }
    public static DataSource getDataSource(){
        return dataSource;
    }
    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
}

C3P0 编写工具类

//拷贝C3PO的jar包
//编写c3p0的xml配置文件c3p0-config.xml
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
    <default-config>
        <property name="driverClass">com.mysql.jdbc.Driver</property>
        <property name="jdbcUrl">jdbc:mysql:///test</property>
        <property name="user">root</property>
        <property name="password">sorry</property>
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
        <property name="maxStatements">200</property>
    </default-config> 
    <named-config name="day15">
        <property name="initialPoolSize">10</property>
        <property name="maxIdleTime">30</property>
        <property name="maxPoolSize">100</property>
        <property name="minPoolSize">10</property>
        <property name="maxStatements">200</property>
    </named-config>
</c3p0-config>


//编写C3P0Util工具类
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.SQLException;
import javax.sql.DataSource;


public class C3POUtil {
    private static ComboPooledDataSource dataSource = new ComboPooledDataSource();

    public static DataSource getDataSource(){
        return dataSource;
    }

    public static Connection getConnection(){
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
    }
}

猜你喜欢

转载自blog.csdn.net/u011456867/article/details/52164981
今日推荐