Druid线程池基础实例

package com.cskaoyan.JDBCDemo;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.io.*;
import java.math.BigDecimal;
import java.sql.*;
import java.util.Properties;

public class DruidDemo {
    public static void main(String[] args) throws Exception {
        Properties info = new Properties();
        //读取文件字符流
        FileReader fileReader = new FileReader("druid.properties");
        //加载配置文件
        info.load(fileReader);
        //创建数据库连接池
        DataSource dataSource = DruidDataSourceFactory.createDataSource(info);
        fileReader.close();
        //获取连接
        Connection connection = dataSource.getConnection();
        //创建预编译执行平台
        Statement statement = connection.createStatement();
        //创建表
        String sql = "create table user(\n" +
                "id int primary key,\n" +
                "username varchar(20),\n" +
                "password varchar(20),\n" +
                "balance decimal(10,2)\n" +
                ")";
        statement.execute(sql);
        //批处理
        String sql1 = "insert into user values(?,?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql1);
        for (int i = 1; i <= 10000; i++) {
            preparedStatement.setInt(1, i + 1);
            preparedStatement.setString(2, "user" + i);
            preparedStatement.setString(3, "password" + i);
            preparedStatement.setDouble(4, i +123);
            preparedStatement.addBatch();
            if (i % 1000 == 0) {
                preparedStatement.executeBatch();
                preparedStatement.clearBatch();
            }
        }
        //打印查询结果
        String sqQuery = "select username,balance from user where balance >10000";
        ResultSet resultSet = statement.executeQuery(sqQuery);
        PrintWriter printWriter = new PrintWriter(new FileWriter("test.txt"));
        printWriter.println("username" + "\t" +"balance");
        while (resultSet.next()){
            String username = resultSet.getNString("username");
            BigDecimal balance = resultSet.getBigDecimal("balance");
            printWriter.println(username+"\t"+balance);
        }

        printWriter.close();
        connection.close();

    }
}

全部评论

相关推荐

预计下个星期就能开奖吧,哪位老哥来给个准信
华孝子爱信等:对接人上周说的是这周
点赞 评论 收藏
分享
11-03 14:38
重庆大学 Java
AAA求offer教程:我手都抬起来了又揣裤兜了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务