Java表格插入读取到的MySQL表格
时间: 2024-03-20 13:42:08 浏览: 18
要将Java中读取到的MySQL表格插入到另一个MySQL表格中,可以使用JDBC API和MySQL Connector/J驱动程序。以下是一个基本的示例代码,可以读取MySQL数据库中的表格并将其插入到另一个MySQL表格中:
```java
import java.sql.*;
public class InsertMySQLTable {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
// Load the MySQL Connector/J driver
Class.forName("com.mysql.jdbc.Driver");
// Connect to the database
conn = DriverManager.getConnection("jdbc:mysql://localhost/mydatabase", "username", "password");
// Create a statement
stmt = conn.createStatement();
// Execute a query to select data from the source table
rs = stmt.executeQuery("SELECT * FROM sourcetable");
// Insert the data into the destination table
PreparedStatement ps = conn.prepareStatement("INSERT INTO destinationtable (id, name, age) VALUES (?, ?, ?)");
while (rs.next()) {
ps.setInt(1, rs.getInt("id"));
ps.setString(2, rs.getString("name"));
ps.setInt(3, rs.getInt("age"));
ps.executeUpdate();
}
ps.close();
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
} finally {
// Clean up resources
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
请注意,此示例假定您已经安装了MySQL数据库,并且已经创建了一个名为"mydatabase"的数据库、一个名为"sourcetable"的源表格和一个名为"destinationtable"的目标表格。同时,您需要将"username"和"password"替换为您的MySQL用户名和密码。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)