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();
}
}