JAVA读取指定txt文件数据并输出sql文件插入数据库
时间: 2023-05-16 13:05:59 浏览: 120
可以使用Java的FileReader和BufferedReader类来读取指定的txt文件,然后使用JDBC连接数据库并将数据插入到数据库中。以下是一个简单的示例代码:
```java
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
public class TxtToSql {
public static void main(String[] args) {
String txtFilePath = "path/to/your/txt/file.txt";
String sqlFilePath = "path/to/your/sql/file.sql";
String jdbcUrl = "jdbc:mysql://localhost:3306/your_database";
String username = "your_username";
String password = "your_password";
try {
// Read txt file
BufferedReader br = new BufferedReader(new FileReader(txtFilePath));
String line;
StringBuilder sb = new StringBuilder();
while ((line = br.readLine()) != null) {
// Process each line of txt file
String[] data = line.split(",");
String name = data[0];
int age = Integer.parseInt(data[1]);
String address = data[2];
// Generate SQL insert statement
sb.append("INSERT INTO your_table (name, age, address) VALUES ('")
.append(name).append("', ")
.append(age).append(", '")
.append(address).append("');\n");
}
br.close();
// Write SQL file
FileWriter fw = new FileWriter(sqlFilePath);
fw.write(sb.toString());
fw.close();
// Insert data into database
Connection conn = DriverManager.getConnection(jdbcUrl, username, password);
PreparedStatement ps = conn.prepareStatement(sb.toString());
ps.executeUpdate();
ps.close();
conn.close();
System.out.println("Data inserted successfully!");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,此代码仅供参考,并且可能需要根据您的具体情况进行修改。