zoukankan      html  css  js  c++  java
  • 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://localhost:3306/mydb?characterEncoding=GBK</property>
            <property name="user">root</property>
            <property name="password"></property>
            
        </default-config>
    </c3p0-config>

    public static void main(String[] args) throws Exception{        
            ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
            DataSource ds = (DataSource) context.getBean("dataSource");        
            Connection conn =  ds.getConnection();        
            conn.close();
        }

    方法二:直接在类文件中连接数据库

    public static void main00(String[] args) throws Exception {
            ComboPooledDataSource ds = new ComboPooledDataSource();
         //依次设置连接数据库的各项属性
            ds.setDriverClass("com.mysql.jdbc.Driver");
            ds.setJdbcUrl("jdbc:mysql://localhost:3306/mydb");
            ds.setUser("root");
            ds.setPassword("");
            ds.setMinPoolSize(5);
            ds.setMaxPoolSize(20);        
            Connection conn =  ds.getConnection();        
            conn.close();            
        }

     

    方法三:使用外置properties文件连接数据库

    c3p0.properties(文件名必须这样

    c3p0.jdbcUrl=jdbc:mysql://localhost:3306/mydb
    c3p0.driverClass=com.mysql.jdbc.Driver
    c3p0.user=root
    c3p0.password=
    
    c3p0.maxPoolSize=20
    c3p0.minPoolSize=5
    c3p0.initialPoolSize=5

    public static void main(String[] args) throws Exception{
            ComboPooledDataSource ds = new ComboPooledDataSource();
            Connection conn = ds.getConnection();
            System.out.println(conn.isClosed()); 
            conn.close();
        }
  • 相关阅读:
    Nginx 启动错误 Failed to read PID from /run/nginx.pid
    CentOS7 下 nginx 无法加载 Django 静态文件的问题
    SSD + 机械硬盘装 CentOS 分区的问题
    CentOS7 单机维护模式
    编译安装 redis 6.2.1
    谷歌师兄刷题笔记
    我用 DCL 写出了单例模式,结果阿里面试官不满意!
    红黑树杀人事件始末
    头条二面:详述一条 SQL 的执行流程
    jvisual远程 springBoot项目
  • 原文地址:https://www.cnblogs.com/jonsnow/p/6641001.html
Copyright © 2011-2022 走看看