**连接MySql数据库,查询出数据,并导出数据到Excel表格.**
public static void main(String[] args) {
//声明Connection对象
Connection con;
//驱动程序名
String driver = "com.mysql.jdbc.Driver";
//URL指向要访问的数据库名mydata
String url = "jdbc:mysql://路径";
//MySQL配置时的用户名
String user = "root";
//MySQL配置时的密码
//String password = "root";
String password = "12345";
//遍历查询结果集
try {
//加载驱动程序
Class.forName(driver);
//1.getConnection()方法,连接MySQL数据库!!
con = (Connection) DriverManager.getConnection(url,user,password);
if(!con.isClosed())
System.out.println("Succeeded connecting to the Database!");
//2.创建statement类对象,用来执行SQL语句!!
Statement statement = (Statement) con.createStatement();
//要执行的SQL语句
String sql = " SELECT * FROM test T ORDER BY t.id asc ";
//3.ResultSet类,用来存放获取的结果集!!
ResultSet rs = statement.executeQuery(sql);
try {
WritableWorkbook wwb = null;
// 创建可写入的Excel工作簿
String fileName = "D://test.xlsx";
File file=new File(fileName);
if (!file.exists()) {
file.createNewFile();
}
//以fileName为文件名来创建一个Workbook
wwb = Workbook.createWorkbook(file);
// 创建工作表
WritableSheet ws = wwb.createSheet("Test Shee 1", 0);
//要插入到的Excel表格的行号,默认从0开始
//第一个为列, 第二个为行, 第三个为值 可以动态添加
Label labelId= new Label(0, 0, "source");//第一列
Label labelName= new Label(1, 0, "target"); //第二列
ws.addCell(labelId);
ws.addCell(labelName);
//写进文档
wwb.write();
// 关闭Excel工作簿对象
wwb.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
rs.close();
con.close();
} catch(ClassNotFoundException e) {
//数据库驱动类异常处理
System.out.println("Sorry,can`t find the Driver!");
e.printStackTrace();
} catch(SQLException e) {
//数据库连接失败异常处理
e.printStackTrace();
}catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
}finally{
System.out.println("数据库数据成功执行!!");
}
}