要使用Java导入MySQL数据库中的制表符分隔文件,您需要遵循以下步骤:
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.27</version>
</dependency>
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String URL = "jdbc:mysql://localhost:3306/your_database_name";
private static final String USERNAME = "your_username";
private static final String PASSWORD = "your_password";
public static Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
public class ImportTSV {
public static void main(String[] args) {
String filePath = "your_tsv_file_path.tsv";
try {
BufferedReader br = new BufferedReader(new FileReader(filePath));
String line;
Connection connection = DatabaseConnection.getConnection();
String sql = "INSERT INTO your_table_name (column1, column2, column3) VALUES (?, ?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
while ((line = br.readLine()) != null) {
String[] values = line.split("\t");
preparedStatement.setString(1, values[0]);
preparedStatement.setString(2, values[1]);
preparedStatement.setString(3, values[2]);
preparedStatement.executeUpdate();
}
preparedStatement.close();
connection.close();
br.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
请注意,您需要根据实际情况替换以下内容:
your_database_name
:您的数据库名称your_username
:您的数据库用户名your_password
:您的数据库密码your_tsv_file_path.tsv
:您的制表符分隔文件的路径your_table_name
:您的数据库表名column1
、column2
、column3
:您的数据库表中的列名以上代码将从制表符分隔文件中读取数据,并将其插入到MySQL数据库表中。请注意,这个示例假设您的数据库表有三个列,您需要根据实际情况调整列数和数据类型。
领取专属 10元无门槛券
手把手带您无忧上云