JDBC案例:模拟用户登录(一)
1、示例代码如下:

package com.jh.www;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Scanner;

public class Test3 {
	public static void main(String[] args) {
		Scanner sc = new Scanner(System.in);
		System.out.println("请输入用户名:");
		String username = sc.nextLine();
		System.out.println("请输入密码:");
		String pswd = sc.nextLine();
		
		boolean b = loginMethod(username,pswd);
		if(b== true) {
			System.out.println("登录成功");
		}else {
			System.out.println("用户名或密码错误");
		}	
	}
//连接查询数据库
public static boolean loginMethod(String user, String password) {
	if (user==null || password==null) {
		return false;
	}
	Connection conn =null;
	Statement stmt = null;
	ResultSet res = null;
	try {
		//1、导入驱动jar包
		//2、注册驱动
//		Class.forName("com.mysql.jdbc.Driver");
		//3、获取数据库的连接对象(连接数据库)url,user,psd
		conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mylb","root","root");
		//4、定义sql
		String sql = "select * from loginUser where name = '"+user+"' and password = "+password+"";
		System.out.println(sql);
		//5、获取执行Sql的对象
		stmt = conn.createStatement();
		//6、执行Sql,接收返回结果
		res =stmt.executeQuery(sql);
		return res.next();
		//7、处理结果
		//8、释放资源
	} catch (SQLException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}finally {
		try {
			res.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			stmt.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		try {
			conn.close();
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	return false;
}
}
Logo

昇腾计算产业是基于昇腾系列(HUAWEI Ascend)处理器和基础软件构建的全栈 AI计算基础设施、行业应用及服务,https://devpress.csdn.net/organization/setting/general/146749包括昇腾系列处理器、系列硬件、CANN、AI计算框架、应用使能、开发工具链、管理运维工具、行业应用及服务等全产业链

更多推荐