1.JDBCConfigUtil.java(JDBC的配置工具类)
package login; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class JDBCConfigUtil { public JDBCConfigUtil(){} //若一个类中的静态方法 public static Connection getConnection(){ Connection con=null; try{ //注册驱动 Class.forName("com.mysql.cj.jdbc.Driver"); //android //Class.forName("com.mysql.jdbc.Driver"); //连接数据库,url地址需要根据实际进行修改 String url="jdbc:mysql://localhost:3306/day1?serverTimezone=UTC&useSSL=false"; String user="root"; //密码需要根据实际情况修改 String password="plj824"; con=DriverManager.getConnection(url,user,password); } catch (SQLException | ClassNotFoundException e) { e.printStackTrace(); } return con; } }
2.JDBCConnectUtil.java(JDBC连接数据库工具类)
import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; public class JDBCConnectUtil { public static boolean userLogin(String username,String psw){ //1.获取数据库连接 Connection con= JDBCConfigUtil.getConnection(); String sql="select * from userinfo where username='"+username+"'"; try { //2.获取SQL语句执行者对象 PreparedStatement pst=con.prepareStatement(sql); //3.执行SQL语句,并得到结果集 ResultSet rs=pst.executeQuery(); //根据结果集中是否有内容(rs.next()方法),进行判断 if(rs.next()){ if(rs.getString("password").equals(psw)){ return true; }else { return false; } }else { return false; } } catch (SQLException e1) { e1.printStackTrace(); } return false; } public static boolean userRegister(String username,String password,String email,String company){ //1.获取数据库连接 Connection con= JDBCConfigUtil.getConnection(); String sql="select * from userinfo where userName='"+username+"'"; try { //2.获取SQL语句执行者对象 PreparedStatement pst=con.prepareStatement(sql); //3.执行SQL语句,并得到结果集 ResultSet rs=pst.executeQuery(); //根据结果集中是否有内容(rs.next()方法),进行判断 if(rs.next()){ return true; }else { HibernateConnectUtil.addUserInfoData(username,password,email,company); return false; } } catch (SQLException e1) { e1.printStackTrace(); } return false; } }