作者:翁松秀
用Java从MySQL查询数据存到CSV文件
在开发和管理MySQL数据库的时候,workbench可以直接从CSV文件中导入数据到MySQL数据库,也可以直接从MySQL数据库中导出数据到CSV文件。但workbench毕竟是手动的,有时候需要解放双手,所以写了一个Java程序,让程序自动从MySQL数据库中查询我们需要的数据,并存到指定目录的CSV文件。
现在假设要查询MySQL用户为"Dennis",密码为"123456",数据库为"myDatabase"中的"user"表中所有记录,并将查询存到D盘根目录下的"user.csv"文件中。
SQL语句
SELECT
*
FROM
user
into outfile 'D:/user.csv'
fields terminated by ','
lines terminated by '\r\n';
into outfile ‘D:/user.csv’ :为指定输出文件路径
fields terminated by ‘,’ :指定字段之间分割
lines terminated by ‘\r\n’ :指定行之间的分割
Java连接MySQL
使用JDBC连接MySQL的时候需要导入一个依赖:mysql-connector-java-5.1.39-bin.jar
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class queryMysqlToCSV{
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/dennis?characterEncoding=utf8&useSSL=false";
static final String USER = "Dennis";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String SQL = null;
try {
//装载驱动
Class.forName(JDBC_DRIVER);
//创建连接
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//执行语句
ps = conn.prepareStatement(SQL);
rs = ps.executeQuery();
//关闭连接
}catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(rs!=null)
rs.close();
if(ps!=null)
ps.close();
if(conn!=null)
conn.close();
}catch(SQLException se) {
se.printStackTrace();
}
}
}
}
在Java中执行SQL语句
package mysql;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class mysqlConnect {
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://localhost:3306/dennis?characterEncoding=utf8&useSSL=false";
static final String USER = "Dennis";
static final String PASS = "123456";
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String SQL = null;
try {
//装载驱动
Class.forName(JDBC_DRIVER);
//创建连接
conn = DriverManager.getConnection(DB_URL,USER,PASS);
//执行语句
SQL = "SELECT \r\n" +
" *\r\n" +
"FROM \r\n" +
" user\r\n" +
"into outfile 'D:/user.csv' " +
"fields terminated by ',' " +
"lines terminated by '\\r\\n'";
ps = conn.prepareStatement(SQL);
rs = ps.executeQuery();
//关闭连接
}catch(SQLException se) {
se.printStackTrace();
}catch(Exception e) {
e.printStackTrace();
}finally {
try {
if(rs!=null)
rs.close();
if(ps!=null)
ps.close();
if(conn!=null)
conn.close();
}catch(SQLException se) {
se.printStackTrace();
}
}
}
}
执行代码会在我们指定的D盘根目录下生成一个user.csv文件。