基于JDBC Java程序在StudentInfo表中插入一条记录,并将表中的记录在控制台中输出,使用PreparedStatement实现。
时间: 2024-03-23 13:42:25 浏览: 21
好的,以下是示例代码:
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class StudentInfoExample {
public static void main(String[] args) {
// 数据库连接信息
String url = "jdbc:mysql://localhost:3306/test";
String user = "root";
String password = "123456";
// SQL语句
String sqlInsert = "INSERT INTO StudentInfo (name, age, gender) VALUES (?, ?, ?)";
String sqlSelect = "SELECT * FROM StudentInfo";
try (Connection conn = DriverManager.getConnection(url, user, password)) {
// 插入数据
PreparedStatement psInsert = conn.prepareStatement(sqlInsert);
psInsert.setString(1, "张三");
psInsert.setInt(2, 20);
psInsert.setString(3, "男");
psInsert.executeUpdate();
// 查询数据
PreparedStatement psSelect = conn.prepareStatement(sqlSelect);
ResultSet rs = psSelect.executeQuery();
while (rs.next()) {
System.out.println(rs.getString("name") + ", " + rs.getInt("age") + ", " + rs.getString("gender"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
该示例使用了JDBC连接MySQL数据库,首先定义了数据库连接信息,然后定义了SQL语句。在try语句块中,先使用PreparedStatement插入数据,然后再使用PreparedStatement查询数据,并将结果输出到控制台。PreparedStatement可以有效防止SQL注入攻击。