java读取csv文件数据 写入mysql
时间: 2023-10-11 21:02:44 浏览: 109
Java读取CSV文件的数据并写入MySQL可以通过以下步骤完成:
1. 首先,你需要使用Java中的FileReader类来读取CSV文件。可以使用CSVReader或者BufferedReader来逐行读取CSV文件的内容。
2. 在读取CSV文件的同时,你可以使用StringTokenizer或者split方法将每一行数据拆分成字段,以便后续写入到MySQL中。
3. 接下来,你需要使用Java中的JDBC(Java Database Connectivity)来连接MySQL数据库。在连接数据库之前,你需要下载并添加数据库驱动程序(JDBC驱动)到你的Java项目中。
4. 一旦连接到MySQL数据库,你可以使用PreparedStatement准备SQL语句,并使用setString或者setInt等方法设置参数的值,将数据插入到MySQL数据库中。
5. 最后,你可以通过执行PreparedStatement的executeUpdate方法来执行SQL插入语句,并将CSV文件中的数据写入到MySQL数据库表中。
以下是一个简单的示例代码,用于读取CSV文件并将数据写入到MySQL数据库:
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class CSVtoMySQLExample {
public static void main(String[] args) {
String csvFilePath = "path_to_csv_file.csv";
String jdbcURL = "jdbc:mysql://localhost:3306/db_name";
String username = "your_username";
String password = "your_password";
try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
BufferedReader br = new BufferedReader(new FileReader(csvFilePath))) {
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
String sql = "INSERT INTO table_name (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, data[0]);
statement.setString(2, data[1]);
statement.setString(3, data[2]);
statement.executeUpdate();
}
System.out.println("Data imported successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,以上代码仅作为示例,你需要根据你的实际情况修改数据库连接信息、CSV文件路径以及插入数据的SQL语句。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)