JDBCUtil.closeConnection(conn,stmt,rs);
时间: 2024-02-19 14:01:02 浏览: 119
这是一个自定义的工具类方法,用于关闭 JDBC 相关的连接和资源。其中 conn 是数据库连接对象,stmt 是执行 SQL 语句的对象,rs 是查询结果集对象。
在 Java 中,使用 JDBC 连接数据库时,需要手动关闭相应的连接和资源,否则会导致资源泄露和程序性能降低。使用这个方法可以方便地关闭连接和资源,并且避免了代码重复和错误。
该方法的实现通常是使用 try-catch-finally 块,先关闭结果集,再关闭语句对象,最后关闭连接对象。在关闭时需要判断对象是否为空,否则会抛出 NullPointerException 异常。
相关问题
根据以下要求写出具体代码:1、基于AJAX技术,在用户注册时,校验用户名是否在数据已存在数据库中。 1)若存在,点击登录按钮,在用户登录页面login.html,完成登录系统操作; 2)若不存在,点击注册按钮,进入注册页面 ,并在register.html页面完成注册。 设计思路: 1.视图层:register.html、login.html。 2.Servlet层: 1)LoginServlet.java //1. 获取到请求中的参数; //2. 和数据库中的内容进行比较; //3. 如果比较通过,创建会话,返回响应状态码; 2)RegisterServlet.java //1.获取请求用户名、密码等; //2.通过用户名查询对象; //3.将注册的用户信息插入数据库 3. Model层如何处理数据: 1)针对用户表的操作UserDao.Java 2)Javabean:User.java 3)jdbc数据库连接:JdbcUtil.java
以下是一个基于AJAX技术的用户注册和登录系统的代码示例:
register.html
```
<!DOCTYPE html>
<html>
<head>
<title>用户注册</title>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
function checkUser() {
var username = $("#username").val();
$.ajax({
url: "checkUser",
type: "POST",
data: {username: username},
dataType: "json",
success: function(data) {
if (data.exist) {
alert("该用户名已存在,请直接登录!");
location.href = "login.html";
} else {
location.href = "register.html";
}
},
error: function() {
alert("服务器出错!");
}
});
}
</script>
</head>
<body>
<h1>用户注册</h1>
<form action="register" method="POST">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password">
<br><br>
<input type="button" value="检查用户名" onclick="checkUser()">
<input type="submit" value="注册">
</form>
</body>
</html>
```
login.html
```
<!DOCTYPE html>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<h1>用户登录</h1>
<form action="login" method="POST">
<label for="username">用户名:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="password">密码:</label>
<input type="password" id="password" name="password">
<br><br>
<input type="submit" value="登录">
</form>
</body>
</html>
```
LoginServlet.java
```
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDao userDao = new UserDao();
User user = userDao.queryByUsername(username);
if (user != null && user.getPassword().equals(password)) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
response.setStatus(200);
} else {
response.sendError(401);
}
}
}
```
RegisterServlet.java
```
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class RegisterServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String password = request.getParameter("password");
UserDao userDao = new UserDao();
User user = userDao.queryByUsername(username);
if (user != null) {
response.sendError(400);
} else {
userDao.addUser(new User(username, password));
response.setStatus(200);
}
}
}
```
UserDao.java
```
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class UserDao {
public User queryByUsername(String username) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
User user = null;
try {
conn = JdbcUtil.getConnection();
stmt = conn.prepareStatement("SELECT * FROM user WHERE username = ?");
stmt.setString(1, username);
rs = stmt.executeQuery();
if (rs.next()) {
user = new User(rs.getInt("id"), rs.getString("username"), rs.getString("password"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(rs, stmt, conn);
}
return user;
}
public void addUser(User user) {
Connection conn = null;
PreparedStatement stmt = null;
try {
conn = JdbcUtil.getConnection();
stmt = conn.prepareStatement("INSERT INTO user(username, password) VALUES (?, ?)");
stmt.setString(1, user.getUsername());
stmt.setString(2, user.getPassword());
stmt.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
JdbcUtil.close(stmt, conn);
}
}
}
```
User.java
```
public class User {
private int id;
private String username;
private String password;
public User(int id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public User(String username, String password) {
this.username = username;
this.password = password;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
```
JdbcUtil.java
```
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class JdbcUtil {
private static String url = "jdbc:mysql://localhost:3306/dbname";
private static String user = "username";
private static String password = "password";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(ResultSet rs, PreparedStatement stmt, Connection conn) {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(PreparedStatement stmt, Connection conn) {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
```
写一个JDBCUtil工具类
JDBCUtil是一个用于管理JDBC连接的工具类。它可以帮助你轻松地创建、释放和管理数据库连接,同时也提供了一些方便的方法来执行SQL语句和获取结果集。
以下是一个JDBCUtil工具类的示例:
```java
import java.sql.*;
public class JDBCUtil {
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql://localhost:3306/test";
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName(DRIVER);
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
return conn;
}
public static void release(Connection conn, Statement stmt, ResultSet rs) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void execute(String sql) {
Connection conn = null;
Statement stmt = null;
try {
conn = getConnection();
stmt = conn.createStatement();
stmt.execute(sql);
} catch (SQLException e) {
e.printStackTrace();
} finally {
release(conn, stmt, null);
}
}
public static ResultSet executeQuery(String sql) {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
conn = getConnection();
stmt = conn.createStatement();
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
}
```
这个工具类包含了以下几个方法:
- `getConnection()`:获取数据库连接。
- `release(Connection conn, Statement stmt, ResultSet rs)`:释放数据库资源。
- `execute(String sql)`:执行SQL语句。
- `executeQuery(String sql)`:执行查询语句并返回结果集。
你可以通过以下方式来使用这个工具类:
```java
public static void main(String[] args) {
Connection conn = JDBCUtil.getConnection();
Statement stmt = null;
ResultSet rs = null;
try {
stmt = conn.createStatement();
rs = stmt.executeQuery("SELECT * FROM user");
while (rs.next()) {
System.out.println(rs.getString("username"));
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
JDBCUtil.release(conn, stmt, rs);
}
}
```
上面的代码中,我们首先使用`getConnection()`方法获取数据库连接,然后利用这个连接创建一个`Statement`对象并执行查询语句。最后,我们使用`release()`方法释放数据库资源。
阅读全文