JDBC使用者名稱和密碼登入
阿新 • • 發佈:2019-01-06
package yt052101; import java.security.interfaces.RSAKey; import java.sql.*; import java.util.*; public class JDBC { public static void main(String[] args) { List<Employee> list = fetchDate(); for(Employee e:list){ System.out.println(e); } Employee employee =login("yun", "ffh1"); if(employee!=null){ System.out.println("登陸成功!歡迎"+employee.getDnama()); }else{ System.out.println("登入失敗,請重新登入"); } } private static Employee login(String dname,String dcount){ Employee employee=null; Connection conn=null; try { Class.forName("org.gjt.mm.mysql.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yun","root","123456"); PreparedStatement ps=conn.prepareStatement("select * from dvds where dname=? and dcount=?"); ps.setString(1, dname); ps.setString(2, dcount); ResultSet rs=ps.executeQuery(); if(rs.next()){ employee = new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4)); } } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); }finally { if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return employee; } private static ArrayList<Employee> fetchDate() { ArrayList<Employee> list=new ArrayList<Employee>(); Employee employee =null; Connection conn=null; //載入驅動程式 try { Class.forName("org.gjt.mm.mysql.Driver"); conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/yun","root","123456"); Statement sm=conn.createStatement(); String string="select * from dvds"; ResultSet rs=sm.executeQuery(string); while(rs.next()){ employee=new Employee(rs.getInt(1),rs.getString(2),rs.getString(3),rs.getInt(4)); list.add(employee); } } catch (ClassNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); }finally { if(conn!=null){ try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } return list; } }