Java实现mysql数据库的导入导出的代码
时间: 2023-02-22 07:33:27 浏览: 131
java调用mysql命令 导入导出数据库
Java实现MySQL数据库的导入导出需要使用JDBC驱动。下面是一个示例代码:
导出:
```
import java.io.File;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
public class Export {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM users");
FileWriter fileWriter = new FileWriter(new File("users.csv"));
while (resultSet.next()) {
fileWriter.append(resultSet.getString(1));
fileWriter.append(",");
fileWriter.append(resultSet.getString(2));
fileWriter.append(",");
fileWriter.append(resultSet.getString(3));
fileWriter.append("\n");
}
fileWriter.flush();
fileWriter.close();
resultSet.close();
statement.close();
connection.close();
System.out.println("导出成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
导入:
```
import java.io.BufferedReader;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
public class Import {
public static void main(String[] args) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement statement = connection.createStatement();
BufferedReader bufferedReader = new BufferedReader(new FileReader(new File("users.csv")));
String line;
while ((line = bufferedReader.readLine()) != null) {
String[] data = line.split(",");
statement.executeUpdate("INSERT INTO users (id, name, email) VALUES ('" + data[0] + "', '" + data[1] + "', '" + data[2] + "')");
}
bufferedReader.close();
statement.close();
connection.close();
System.out.println("导入成功");
} catch (Exception e) {
e.printStackTrace();
}
}
}
```
请注意,上面的代码仅作为示例,
阅读全文