java txt导入mysql
时间: 2023-06-30 15:25:50 浏览: 43
你可以使用Java中的JDBC连接MySQL数据库,然后使用FileReader和BufferedReader从txt文件中读取数据,最后使用SQL语句将数据插入到MySQL数据库中。以下是一个简单的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class TxtToMysql {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String password = "123456";
String sql = "INSERT INTO mytable (col1, col2, col3) VALUES (?, ?, ?)";
try (Connection conn = DriverManager.getConnection(url, user, password);
PreparedStatement pstmt = conn.prepareStatement(sql)) {
BufferedReader br = new BufferedReader(new FileReader("data.txt"));
String line;
while ((line = br.readLine()) != null) {
String[] data = line.split(",");
pstmt.setString(1, data[0]);
pstmt.setString(2, data[1]);
pstmt.setString(3, data[2]);
pstmt.executeUpdate();
}
br.close();
} catch (SQLException | IOException e) {
e.printStackTrace();
}
}
}
```
其中,url、user和password分别是MySQL数据库的连接信息,sql是要执行的SQL语句,mytable是要插入数据的表名,col1、col2、col3是表中的列名,可以根据实际情况修改。在while循环中,逐行读取txt文件中的数据,使用split方法将每行数据按逗号分隔成数组,然后将数据插入到MySQL数据库中。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.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)