import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCTest {
public static void main(String[] args) throws IOException {
String user_id1 = "";//保存user_id
File file = new File("d:\\initial_id.txt");
FileWriter os = new FileWriter(file);
BufferedWriter initial_bw = new BufferedWriter(os);//为initial_id创建一个文件
File file1 = new File("d:\\user_id1.txt");
FileWriter os1 = new FileWriter(file1);
BufferedWriter user_bw = new BufferedWriter(os1);//为user_id1创建一个文件
try {
Class.forName("com.mysql.jdbc.Driver");// 加载驱动程序
String url = "jdbc:mysql://10.10.10.12:#####/#####";// URL指向要访问的数据库名
String user = "root";// MySQL配置时的用户名
String password = "#############";// MySQL配置时的密码
Connection connection = DriverManager.getConnection(url, user,password);// 连续数据库
if (!connection.isClosed()){
System.out.println("Succeeded connecting to the Database!");
}
Statement statement = connection.createStatement();// statement用来执行SQL语句
System.out.println("user_id1" + "\t" + "initial_id");
initial_bw.append("initial_id");
initial_bw.newLine();//打印标题
user_bw.append("user_id1");
user_bw.newLine();//打印标题
for(int i=0;i<400;i++){
String sqlname="user_message_"+i;
String sql = "select user_id1,initial_id from "+sqlname+" group by initial_id order by user_id1 limit 250";// 要执行的SQL语句 www.2cto.com
ResultSet rs = statement.executeQuery(sql);// 执行SQL语句并返回结果集
while (rs.next()) {
//System.out.println(rs.getString("initial_id") + "\t"+ rs.getString("user_id1"));
if(!user_id1.equals(rs.getString("user_id1"))&user_id1.equals(""))
{
user_bw.append(rs.getString("user_id1"));
user_bw.newLine();
initial_bw.append(rs.getString("initial_id"));
}
else if (!user_id1.equals(rs.getString("user_id1"))) {
user_bw.append(rs.getString("user_id1"));
user_bw.newLine();
initial_bw.newLine();
initial_bw.append(rs.getString("initial_id"));
}
else
{
initial_bw.append(","+rs.getString("initial_id"));
}
user_id1 = rs.getString("user_id1");
}
rs.close();//关闭果集
}
System.out.println("恭喜您!数据生成结束");
connection.close();//数据库连接
initial_bw.flush();
user_bw.flush();
} catch (ClassNotFoundException e) {
// 如果连接数据库失败就会报异常
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}