使用statement和preparedStatement执行sql语句的代码示例
时间: 2024-06-15 14:06:47 浏览: 99
详解JSP中的语句对象Statement操作MySQL的使用实例
以下是使用Statement和PreparedStatement执行SQL语句的代码示例:
1. 使用Statement执行SQL语句[^1]:
```java
import java.sql.*;
public class StatementExample {
public static void main(String[] args) {
try {
// 建立数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 创建Statement对象
Statement stmt = conn.createStatement();
// 执行SQL查询语句
String sql = "SELECT * FROM mytable";
ResultSet rs = stmt.executeQuery(sql);
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// 关闭连接
rs.close();
stmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
2. 使用PreparedStatement执行SQL语句[^2]:
```java
import java.sql.*;
public class PreparedStatementExample {
public static void main(String[] args) {
try {
// 建立数据库连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "username", "password");
// 创建PreparedStatement对象
String sql = "SELECT * FROM mytable WHERE id = ?";
PreparedStatement pstmt = conn.prepareStatement(sql);
// 设置参数
pstmt.setInt(1, 1);
// 执行查询
ResultSet rs = pstmt.executeQuery();
// 处理查询结果
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
System.out.println("ID: " + id + ", Name: " + name);
}
// 关闭连接
rs.close();
pstmt.close();
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
阅读全文