java jtable增删改查,java swing jdbc sql 增删改查 实例1
时间: 2023-11-27 15:04:54 浏览: 104
JAVA swing界面实现数据库增删改查.pdf
5星 · 资源好评率100%
好的,下面是一个简单的示例代码,演示如何在Java Swing中使用JDBC和SQL实现JTable的增删改查功能。
1. 首先,需要创建一个JTable对象并将其添加到JFrame中:
```
JTable table = new JTable();
JScrollPane scrollPane = new JScrollPane(table);
frame.add(scrollPane);
```
2. 接下来,需要连接数据库并执行SQL查询来获取数据:
```
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
```
3. 将查询结果添加到JTable中:
```
DefaultTableModel model = new DefaultTableModel();
model.addColumn("ID");
model.addColumn("Name");
while (rs.next()) {
Object[] row = new Object[2];
row[0] = rs.getInt("id");
row[1] = rs.getString("name");
model.addRow(row);
}
table.setModel(model);
```
4. 实现添加数据的方法:
```
public void addData(String name) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String query = "INSERT INTO mytable(name) VALUES(?)";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.executeUpdate();
refreshTable();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
```
5. 实现删除数据的方法:
```
public void deleteData(int id) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String query = "DELETE FROM mytable WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setInt(1, id);
pstmt.executeUpdate();
refreshTable();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
```
6. 实现更新数据的方法:
```
public void updateData(int id, String name) {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
String query = "UPDATE mytable SET name=? WHERE id=?";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setString(1, name);
pstmt.setInt(2, id);
pstmt.executeUpdate();
refreshTable();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
```
7. 最后,实现刷新JTable的方法:
```
public void refreshTable() {
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "password");
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM mytable");
DefaultTableModel model = new DefaultTableModel();
model.addColumn("ID");
model.addColumn("Name");
while (rs.next()) {
Object[] row = new Object[2];
row[0] = rs.getInt("id");
row[1] = rs.getString("name");
model.addRow(row);
}
table.setModel(model);
} catch (SQLException ex) {
ex.printStackTrace();
}
}
```
这样,就可以实现一个简单的Java Swing应用程序,包含JTable的增删改查功能了。
阅读全文