优化这段代码CREATE TABLE user ( id INT PRIMARY KEY AUTO_INCREMENT, username VARCHAR(50) NOT NULL, password VARCHAR(50) NOT NULL); import java.sql.*; public class UserDAO { private final String url = "jdbc:mysql://localhost:3306/mydb"; private final String user = "username"; private final String password = "password"; public boolean register(String username, String password) { try (Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement stmt = conn.prepareStatement( "INSERT INTO user (username, password) VALUES (?, ?)")) { stmt.setString(1, username); stmt.setString(2, password); int rows = stmt.executeUpdate(); return rows > 0; } catch (SQLException e) { e.printStackTrace(); return false; } } public boolean login(String username, String password) { try (Connection conn = DriverManager.getConnection(url, user, password); PreparedStatement stmt = conn.prepareStatement( "SELECT * FROM user WHERE username = ? AND password = ?")) { stmt.setString(1, username); stmt.setString(2, password); ResultSet rs = stmt.executeQuery(); return rs.next(); } catch (SQLException e) { e.printStackTrace(); return false; } } }
时间: 2024-04-26 15:26:39 浏览: 104
首先,建议将数据库连接池引入代码中,以避免每次调用数据库时都要重新连接。这将大大减少连接和关闭数据库的开销。
其次,建议使用预编译语句,以避免每次执行 SQL 语句时都要重新编译。这也将大大减少编译和执行 SQL 语句的开销。
最后,可以在数据库中添加索引以加快查询速度。在这个例子中,可以在 username 和 password 字段上创建索引。
下面是经过优化的代码:
import java.sql.*;
import javax.sql.DataSource;
import org.apache.commons.dbcp2.BasicDataSource;
public class UserDAO {
private DataSource dataSource;
public UserDAO() {
BasicDataSource ds = new BasicDataSource();
ds.setUrl("jdbc:mysql://localhost:3306/mydb");
ds.setUsername("username");
ds.setPassword("password");
ds.setInitialSize(5);
dataSource = ds;
}
public boolean register(String username, String password) {
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(
"INSERT INTO user (username, password) VALUES (?, ?)")) {
stmt.setString(1, username);
stmt.setString(2, password);
int rows = stmt.executeUpdate();
return rows > 0;
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
public boolean login(String username, String password) {
try (Connection conn = dataSource.getConnection();
PreparedStatement stmt = conn.prepareStatement(
"SELECT * FROM user WHERE username = ? AND password = ?")) {
stmt.setString(1, username);
stmt.setString(2, password);
ResultSet rs = stmt.executeQuery();
return rs.next();
} catch (SQLException e) {
e.printStackTrace();
return false;
}
}
}
阅读全文