• ADADADADAD

    mysql怎么使用连接池[ 建站问答 ]

    建站问答 时间:2024-12-01 19:01:55

    作者:文/会员上传

    简介:

    mysql使用连接池的示例:1.手动配置连接池。/***手动设置连接池*/publicvoiddemo1(){//获得连接:Connectionconn=null;PreparedStatementpstmt=null;ResultSetrs=null;try{//

    以下为本文的正文内容,内容仅供参考!本站为公益性网站,复制本文以及下载DOC文档全部免费。

    mysql使用连接池的示例:

    1.手动配置连接池。

    /**

    *手动设置连接池

    */

    publicvoiddemo1(){

    //获得连接:

    Connectionconn=null;

    PreparedStatementpstmt=null;

    ResultSetrs=null;

    try{

    //创建连接池:

    ComboPooledDataSourcedataSource=newComboPooledDataSource();

    //设置连接池的参数:

    dataSource.setDriverClass("com.mysql.jdbc.Driver");

    dataSource.setJdbcUrl("jdbc:mysql:///jdbctest");

    dataSource.setUser("root");

    dataSource.setPassword("abc");

    dataSource.setMaxPoolSize(20);

    dataSource.setInitialPoolSize(3);

    //获得连接:

    conn=dataSource.getConnection();

    //编写Sql:

    Stringsql="select*fromuser";

    //预编译SQL:

    pstmt=conn.prepareStatement(sql);

    //设置参数

    //执行SQL:

    rs=pstmt.executeQuery();

    while(rs.next()){

    System.out.println(rs.getInt("uid")+""+rs.getString("username")+""+rs.getString("password")+""+rs.getString("name"));

    }

    }catch(Exceptione){

    e.printStackTrace();

    }finally{

    JDBCUtils.release(rs,pstmt,conn);

    }

    }

    2.使用配置文件配置连接池,配置文件xml如下:

    <?xmlversion="1.0"encoding="UTF-8"?>

    <c3p0-config>

    <default-config>

    <propertyname="driverClass">com.mysql.jdbc.Driver</property>

    <propertyname="jdbcUrl">jdbc:mysql:///jdbctest</property>

    <propertyname="user">root</property>

    <propertyname="password">abc</property>

    <propertyname="initialPoolSize">5</property>

    <propertyname="maxPoolSize">20</property>

    </default-config>

    </c3p0-config>

    3.使用配置文件。

    /**

    *使用配置文件的方式

    */

    publicvoiddemo2(){

    Connectionconn=null;

    PreparedStatementpstmt=null;

    ResultSetrs=null;

    try{

    /*//获得连接:

    ComboPooledDataSourcedataSource=newComboPooledDataSource();*/

    //获得连接:

    //conn=dataSource.getConnection();

    conn=JDBCUtils2.getConnection();

    //编写Sql:

    Stringsql="select*fromuser";

    //预编译SQL:

    pstmt=conn.prepareStatement(sql);

    //设置参数

    //执行SQL:

    rs=pstmt.executeQuery();

    while(rs.next()){

    System.out.println(rs.getInt("uid")+""+rs.getString("username")+""+rs.getString("password")+""+rs.getString("name"));

    }

    }catch(Exceptione){

    e.printStackTrace();

    }finally{

    JDBCUtils2.release(rs,pstmt,conn);

    }

    }

    mysql怎么使用连接池.docx

    将本文的Word文档下载到电脑

    推荐度:

    下载