Java读取csv文件数据到mysql数据库,存入数据带引号
时间: 2024-10-25 14:12:15 浏览: 9
java中读取shp文件数据存入数据库
在Java中,读取CSV文件并将其数据存储到MySQL数据库中,通常需要通过流式处理、分隔符解析以及SQL插入操作来完成。这里是一个简单的示例,使用`OpenCSV`库读取CSV文件,`JDBC`连接MySQL:
首先,你需要添加依赖:
```xml
<dependency>
<groupId>com.opencsv</groupId>
<artifactId>opencsv</artifactId>
<version>5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.x</version> <!-- 根据实际版本替换 -->
</dependency>
```
然后,你可以编写如下Java代码:
```java
import com.opencsv.CSVReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class CSVToMySQL {
private static final String CSV_FILE_PATH = "path_to_your_file.csv";
private static final String MYSQL_URL = "jdbc:mysql://localhost:3306/your_database";
private static final String USER = "your_username";
private static final String PASSWORD = "your_password";
public static void main(String[] args) {
try (Connection connection = DriverManager.getConnection(MYSQL_URL, USER, PASSWORD);
CSVReader reader = new CSVReader(new FileReader(CSV_FILE_PATH))) {
String[] line;
while ((line = reader.readNext()) != null) {
// 分割每一行数据(假设逗号作为分隔符)
String field1 = line[0];
String field2 = line[1];
// 需要处理字段中的引号,比如转义成两个''
String quotedField1 = escapeQuotes(field1);
String quotedField2 = escapeQuotes(field2);
// 构造SQL插入语句并执行
String sql = "INSERT INTO your_table (field1, field2) VALUES (?, ?)";
PreparedStatement statement = connection.prepareStatement(sql);
statement.setString(1, quotedField1);
statement.setString(2, quotedField2);
statement.executeUpdate();
}
} catch (Exception e) {
System.err.println("Error reading CSV or writing to MySQL: " + e.getMessage());
}
}
// 辅助方法,用于处理字符串中的引号
private static String escapeQuotes(String str) {
return str.replace("'", "''");
}
}
```
阅读全文