MySQL第三天

本文介绍了一个简单的Java程序,该程序使用JDBC工具类实现数据库连接,并通过输入用户名和密码进行登录验证。文章提供了完整的代码示例,包括异常处理和资源关闭。
//连接数据库的工具类
public class JDBCUtils {

private static final String USER="root";
private static final String PWD="root";
private static final String URL="jdbc:mysql://localhost:3306/girl";
private static final String DRIVER="com.mysql.jdbc.Driver";
//1.注册驱动
static {
try {
Class.forName(DRIVER);
} catch (Exception e){
e.printStackTrace();
}
}
//2.得到数据库连接
public static Connection getConnetion() throws SQLException{
return (Connection) DriverManager.getConnection(URL,USER,PWD);
}
//3.关闭资源
public static void close(Connection con, Statement stat){
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement stat,ResultSet rs){
if (rs!=null){
try {
rs.close();
}catch (Exception e){
e.printStackTrace();
}
}
if(stat!=null){
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//登陆实现
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名");
String name= sc.nextLine();
System.out.println("请输入密码");
String password=sc.nextLine();
login(name,password);
}
//1.写一个登陆方法
public static void login(String name,String password){
Connection con = null;
Statement stat= null;
ResultSet rs= null;
try {
//1.通过工具类获得链接
con= JDBCUtils.getConnetion();
//2.定义sql
String sql ="select*from yang where ename='"+name+"'and mgr ='"+password+"'";
//3.获取执行对象
stat=con.createStatement();
System.out.println(sql);
//4.查询数据库 如果有记录 表示登录成功 否则登录失败
rs=stat.executeQuery(sql);
if (rs.next()){
System.out.println("登陆成功");
}else {
System.out.println("登陆失败");
}
} catch (Exception e){
e.printStackTrace();
}finally {
JDBCUtils.close(con,stat,rs);
}
}
 

转载于:https://www.cnblogs.com/Y-mmeng/p/10673077.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值