将数据库数据写入.csv文件
您可以使用OpenCSV库将数据写入.csv文件,并可以使用mysql-java-connector通过Java程序与MySQL数据库进行通信。
Maven依赖
以下是您需要包含在pom.xml文件中才能将数据库表中的数据写入.csv文件的依赖项。
<dependency> <groupId>com.opencsv</groupId> <artifactId>opencsv</artifactId> <version>4.4</version> </dependency> <dependency> <groupId>org.apache.commons</groupId> <artifactId>commons-lang3</artifactId> <version>3.9</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.6</version> </dependency>
将数据写入CSV文件
com.opencsv包的CSVWriter类表示一个简单的CSV写入器。实例化此类时,需要将表示目标文件的Writer对象作为参数传递给其构造函数。它提供名为**writeAll()**和**writeNext()**的方法来将数据写入.csv文件。
使用writeNext()方法
CSVWriter类的writeNext()方法将下一行写入.csv文件。
示例
假设我们创建了一个名为empDetails的表,并使用以下查询填充了它:
CREATE TABLE empDetails (ID INT, Name VARCHAR(255), Salary INT, start_date VARCHAR(255), Dept VARCHAR(255)); Insert INTO empDetails values (1, 'Krishna', 2548, '2012-01-01', 'IT'); Insert INTO empDetails values (2, 'Vishnu', 4522, '2013-02-26', 'Operations'); Insert INTO empDetails values (3, 'Raja', 3021, '2016-10-10', 'HR'); Insert INTO empDetails values (4, 'Raghav', 6988, '2012-01-01', 'IT');
以下Java程序根据上面创建的表创建一个csv文件。
import java.io.FileWriter; import java.io.IOException; import java.sql.Connection; import java.sql.DriverManager; import java.sql.ResultSet; import java.sql.ResultSetMetaData; import java.sql.SQLException; import java.sql.Statement; import com.opencsv.CSVWriter; public class DbToCSV { public static void main(String args[]) throws SQLException, IOException { //Getting the connection String url = "jdbc:mysql://127.0.0.1/mydb"; Connection con = DriverManager.getConnection(url, "root", "password"); System.out.println("Connection established......"); //Creating the Statement Statement stmt = con.createStatement(); //Query to retrieve records String query = "Select * from empDetails"; //Executing the query stmt.executeQuery("use mydb"); ResultSet rs = stmt.executeQuery(query); //Instantiating the CSVWriter class CSVWriter writer = new CSVWriter(new FileWriter("D://output.csv")); ResultSetMetaData Mdata = rs.getMetaData(); Mdata.getColumnName(1); //Writing data to a csv file String line1[] = {Mdata.getColumnName(1), Mdata.getColumnName(2), Mdata.getColumnName(3), Mdata.getColumnName(4), Mdata.getColumnName(5)}; writer.writeNext(line1); String data[] = new String[5]; while(rs.next()) { data[0] = new Integer(rs.getInt("ID")).toString(); data[1] = rs.getString("Name"); data[2] = new Integer(rs.getInt("Salary")).toString(); data[3] = rs.getString("start_date"); data[4] = rs.getString("Dept"); writer.writeNext(data); } //Flushing data from writer to file writer.flush(); System.out.println("Data entered"); } }
输出
Connection established...... Data entered
如果您验证生成的.csv文件,您可以观察到其内容如下:
"ID","Name","Salary","start_date","Dept" "1","Krishna","2548","2012-01-01","IT" "2","Vishnu","4522","2013-02-26","Operations" "3","Raja","3021","2016-10-10","HR" "4","Raghav","6988","2012-01-01","IT"
广告