编写java源程序LX2.java,实现连接数据库tongxun,实现对ben表的动态操作(要求用预编译方法实现动态SQL语句的执行)。 (1) 查询表中的记录 (2) 向数据表中插入记录 (3) 删除数据表中的某条记录 (4) 修改数据表中的记录
时间: 2024-01-27 22:05:16 浏览: 37
以下是LX2.java的源代码,其中使用了预编译方法实现动态SQL语句的执行:
```java
import java.sql.*;
public class LX2 {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/tongxun";
String user = "root";
String password = "123456";
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try {
// 加载数据库驱动程序
Class.forName("com.mysql.jdbc.Driver");
// 建立数据库连接
conn = DriverManager.getConnection(url, user, password);
// 查询表中的记录
pstmt = conn.prepareStatement("SELECT * FROM ben");
rs = pstmt.executeQuery();
while(rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String phone = rs.getString("phone");
System.out.println("id:" + id + ", name:" + name + ", phone:" + phone);
}
// 向数据表中插入记录
pstmt = conn.prepareStatement("INSERT INTO ben(name, phone) VALUES (?, ?)");
pstmt.setString(1, "Tom");
pstmt.setString(2, "123456789");
int rows = pstmt.executeUpdate();
System.out.println("插入" + rows + "条记录");
// 删除数据表中的某条记录
pstmt = conn.prepareStatement("DELETE FROM ben WHERE id = ?");
pstmt.setInt(1, 1);
rows = pstmt.executeUpdate();
System.out.println("删除" + rows + "条记录");
// 修改数据表中的记录
pstmt = conn.prepareStatement("UPDATE ben SET phone = ? WHERE id = ?");
pstmt.setString(1, "987654321");
pstmt.setInt(2, 2);
rows = pstmt.executeUpdate();
System.out.println("修改" + rows + "条记录");
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if(rs != null) rs.close();
if(pstmt != null) pstmt.close();
if(conn != null) conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
```
在这个例子中,我们首先加载MySQL数据库的驱动程序,然后建立与tongxun数据库的连接。接着使用PreparedStatement对象来执行动态SQL语句,通过setXXX()方法设置占位符的值,最后调用executeQuery()、executeUpdate()等方法来执行SQL语句并获取结果。在所有操作完成后,需要关闭数据库连接、PreparedStatement和ResultSet对象。