package com.sjk.service;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.sjk_user.util.GetConnection;
public class UserService {
//登陆
public static String login(String uname,String pwd) throws Exception {
String msg="登陆失败";
Connection conn=GetConnection.getConn();
Statement stmt=conn.createStatement();
String sql="select * from user where username='"+uname+"' and password='"+pwd+"'";
ResultSet rs=stmt.executeQuery(sql);
if(rs.next()) {
msg="登陆成功";
}
conn.close();
stmt.close();
return msg;
}
//注册
public static String register(String uname,String pwd) throws Exception {
String msg="注册失败";
if("存在".equals(fingUserName(uname))) {
msg="用户名已存在";
}else {
Connection conn=GetConnection.getConn();
Statement stmt=conn.createStatement();
String sql="insert into user(username,password) values('"+uname+"','"+pwd+"')";
int count=stmt.executeUpdate(sql);//执行SQL并返回受影响的条数
if(count>0) {
msg="注册成功";
}else {
msg="sql运行错误,注册失败";
}
conn.close();
stmt.close();
}
return msg;
}
//查询用户名是否存在
public static String fingUserName(String uname) throws Exception {
String msg="不存在";
Connection conn=GetConnection.getConn();
Statement stmt=conn.createStatement();
String sql="select * from user where username='"+uname+"'";
ResultSet rs=stmt.executeQuery(sql);
if(rs.next()) {
msg="存在";
}
conn.close();
stmt.close();
return msg;
}
//注销
public static String delUser(String uname,String pwd) throws Exception {
String msg="注销失败";
if("不存在".equals (fingUserName(uname)) ) {
msg="用户名不存在";
}else {
if("登陆成功".equals(login(uname,pwd))) {
Connection conn=GetConnection.getConn();
Statement stmt=conn.createStatement();
String sql="delete from user where username='"+uname+"'";
int count=stmt.executeUpdate(sql);
if(count>0) {
msg="删除成功";
}else{
msg= "sql执行错误,注销失败";
}
conn.close();
stmt.close();
}else {
msg="密码验证失败";
}
}
return msg;
}
}
package com.sjk.test;
import com.sjk.service.UserService;
public class Test1 {
public static void main(String[] args) throws Exception {
//登陆
String s=UserService.login("abc", "444");
System.out.println(s);
//查询用户名是否存在
String result=UserService.fingUserName("张6");
System.out.println(result);
//注册
String result1=UserService.register("张三锋", "1234");
System.out.println(result1);
//注销
String result2=UserService.delUser("abc", "444");
System.out.println(result2);
}
}
package com.sjk_user.util;
import java.sql.Connection;
import java.sql.DriverManager;
public class GetConnection
{
private static String address="jdbc:mysql://localhost:3306/data2?useSSL=true&serverTimezone-UTC";
private static String dataBaseName="root";
private static String dataBasePwd="521616";
public static Connection getConn() {
Connection conn=null;
try {
Class.forName("com.mysql.cj.jdbc.Driver");
conn=DriverManager.getConnection(address, dataBaseName, dataBasePwd);
} catch (Exception e) {
// TODO 自动生成的 catch 块
e.printStackTrace();
System.out.println("连接失败");
}
return conn;
}
}