简单SQLHelper(java)
时间: 2024-03-05 21:53:06 浏览: 66
以下是一个简单的 SQLHelper 类,使用 Java 和 JDBC 进行数据库操作:
```java
import java.sql.*;
public class SQLHelper {
private Connection conn = null;
private Statement stmt = null;
private ResultSet rs = null;
public SQLHelper(String url, String user, String password) throws SQLException {
conn = DriverManager.getConnection(url, user, password);
stmt = conn.createStatement();
}
public ResultSet executeQuery(String sql) throws SQLException {
rs = stmt.executeQuery(sql);
return rs;
}
public int executeUpdate(String sql) throws SQLException {
return stmt.executeUpdate(sql);
}
public void close() throws SQLException {
if (rs != null) rs.close();
if (stmt != null) stmt.close();
if (conn != null) conn.close();
}
}
```
使用该类可以执行 SQL 查询和更新操作。例如,查询语句可以这样执行:
```java
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "root";
SQLHelper sqlHelper = new SQLHelper(url, user, password);
String sql = "SELECT * FROM mytable";
ResultSet rs = sqlHelper.executeQuery(sql);
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
int age = rs.getInt("age");
System.out.println("id=" + id + ", name=" + name + ", age=" + age);
}
sqlHelper.close();
```
更新语句可以这样执行:
```java
String url = "jdbc:mysql://localhost:3306/mydb";
String user = "root";
String password = "root";
SQLHelper sqlHelper = new SQLHelper(url, user, password);
String sql = "UPDATE mytable SET name='Alice' WHERE id=1";
int rowsAffected = sqlHelper.executeUpdate(sql);
System.out.println(rowsAffected + " rows affected");
sqlHelper.close();
```
注意,这只是一个简单的 SQLHelper 类,实际应用中需要考虑更多的异常处理、连接池等问题。
阅读全文