java连接mysql实现用户登录

更新时间:02-11 教程 由 或许 分享

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方法即可实现用户登录验证。

声明:关于《java连接mysql实现用户登录》以上内容仅供参考,若您的权利被侵害,请联系13825271@qq.com
本文网址:http://www.25820.com/tutorial/14_2073934.html