Java连接MySQL实现用户登录
在web应用中,用户登录是一个非常常见的功能,那么如何使用Java连接MySQL实现用户登录呢?
//导入所需包import java.sql.*;//创建数据库连接类public class ConnectionUtil {//静态代码块,加载JDBC驱动static {try {Class.forName("com.mysql.jdbc.Driver");} catch (ClassNotFoundException e) {e.printStackTrace();}}//获取数据库连接public static Connection getConnection() throws SQLException {return DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "123456");}//关闭数据库连接public static void close(Connection conn, Statement stmt, ResultSet rs) {try {if (rs != null) {rs.close();}if (stmt != null) {stmt.close();}if (conn != null) {conn.close();}} catch (SQLException e) {e.printStackTrace();}}}
以上代码实现了MySQL数据库的连接和关闭操作,下面我们来看一下如何实现用户登录功能。
//导入所需的包import java.sql.*;import java.util.*;//创建用户登录类public class UserLogin {//定义静态常量public static final String SUCCESS = "success";public static final String ERROR = "error";//登录方法public static String login(String username, String password) {//定义连接、语句、结果集Connection conn = null;PreparedStatement stmt = null;ResultSet rs = null;String result = ERROR;try {//获取数据库连接conn = ConnectionUtil.getConnection();//定义SQL语句String sql = "select * from user where username=? and password=?";//创建预编译语句stmt = conn.prepareStatement(sql);//设置参数stmt.setString(1, username);stmt.setString(2, password);//执行查询rs = stmt.executeQuery();//判断结果if (rs.next()) {result = SUCCESS;}} catch (SQLException e) {e.printStackTrace();} finally {//关闭数据库连接ConnectionUtil.close(conn, stmt, rs);}return result;}}
以上就是使用Java连接MySQL实现用户登录的完整代码,通过调用login方法即可实现用户登录验证。