帮我写一个方法读取文件到数据库的Java代码和python代码
Java代码:
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class FileToDatabase {
public static void main(String[] args) {
String filePath = "path/to/file.txt";
String jdbcURL = "jdbc:mysql://localhost:3306/mydatabase";
String username = "myusername";
String password = "mypassword";
try (Connection connection = DriverManager.getConnection(jdbcURL, username, password);
PreparedStatement statement = connection.prepareStatement("INSERT INTO mytable (column1, column2) VALUES (?, ?)")) {
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line;
while ((line = reader.readLine()) != null) {
String[] values = line.split(",");
statement.setString(1, values[0]);
statement.setString(2, values[1]);
statement.executeUpdate();
}
reader.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
Python代码:
import mysql.connector
file_path = "path/to/file.txt"
database_name = "mydatabase"
table_name = "mytable"
username = "myusername"
password = "mypassword"
# Connect to database
mydb = mysql.connector.connect(
host="localhost",
user=username,
passwd=password,
database=database_name
)
mycursor = mydb.cursor()
# Open file and insert data into database
with open(file_path, "r") as file:
for line in file:
values = line.split(",")
sql = "INSERT INTO " + table_name + " (column1, column2) VALUES (%s, %s)"
mycursor.execute(sql, (values[0], values[1]))
mydb.commit()
mycursor.close()
mydb.close()
``
原文地址: http://www.cveoy.top/t/topic/cpX6 著作权归作者所有。请勿转载和采集!