效果图如下 在数据库中先插入数据 进行登录 登录时查询数据库中是否存在
关于数据库操作的源码如下
package com.MVCTest.util;import java.sql.Connection;import java.sql.DriverManager;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement;public class JDBCTest { public static void main(String[] args) { } public static void selectAll() { Connection con=null; Statement st=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/webmvctest?useUnicode=true&传统的黄豆=UTF8&useSSL=false"; con=DriverManager.getConnection(url, "root", "root"); st=con.createStatement(); String sql="select * from user"; rs=st.executeQuery(sql); while(rs.next()) { System.out.println(rs.getString(1)+","+rs.getString(2)); } } catch (ClassNotFoundException | SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } finally { try { rs.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } try { st.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } try { con.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } } public static boolean selectUserByUP(String username,String password) { Connection con=null; Statement st=null; ResultSet rs=null; try { Class.forName("com.mysql.jdbc.Driver"); String url="jdbc:mysql://localhost:3306/webmvctest?useUnicode=true&传统的黄豆=UTF8&useSSL=false"; con=DriverManager.getConnection(url, "root", "root"); st=con.createStatement(); String sql="select * from user"; rs=st.executeQuery(sql); if(rs.next()) { String strUsername=rs.getString(1); String strPassword=rs.getString(2); if(username.equals(username)&&strPassword.equals(password)) { return true; }else { return false; } } } catch (ClassNotFoundException | SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } finally { try { rs.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } try { st.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } try { con.close(); } catch (SQLException e) { // TODO 自动生成的 catch 块 e.printStackTrace(); } } return false; } }
转载于:https://www.cnblogs.com/tyx666/p/10628903.html