需求:
1,使用Swing完成用户登录程序。
2,使用Swing完成用户注册程序。
结构:
代码:
BaseDao
package com.frame;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
public class BaseDao {
private Connection conn=null;
private PreparedStatement pstmt=null;
private ResultSet rs=null;
private List params=new ArrayList();//表示SQL的参数
public void setParams(List params) {
this.params = params;
}
public void setPreparedStatement (){
for (int i = 0; i < params.size(); i++) {
try {
pstmt.setObject(i+1, params.get(i));
} catch (Exception e) {
e.printStackTrace();
}
}
}
//连接数据库
public Connection getConnection(){
try {
InputStream in=this.getClass().getResourceAsStream("/db.properties");//在包下获取资源
Properties prop=new Properties();
prop.load(in);//按简单的面向行的格式从输入字符流中读取属性列表(键和元素对)。
Class.forName(prop.getProperty("driver"));//返回与带有给定字符串名的类或接口相关联的 Class 对象。
return DriverManager.getConnection(prop.getProperty("url"),prop.getProperty("user"), prop.getProperty("password"));
//试图建立到给定数据库 URL 的连接。
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}
}
//增删改
public int update(String sql){
conn=getConnection();
try {
pstmt=conn.prepareStatement(sql);
this.setPreparedStatement();
return pstmt.executeUpdate();
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return 0;
}finally{
close();
}
}
//利用反射改造查询方法
public List query(String sql,Class cls){
List list=new ArrayList();
conn=getConnection();
try {
pstmt=conn.prepareStatement(sql);
this.setPreparedStatement();
ResultSet rs=pstmt.executeQuery();
while(rs.next()){
Object obj=cls.newInstance();
Field[]fs=cls.getDeclaredFields();
for (Field f : fs) {
Method m=cls.getDeclaredMethod("set"+f.getName().substring(0,1).toUpperCase()+f.getName().substring(1),f.getType());
m.invoke(obj, rs.getObject(f.getName()));
}
list.add(obj);
}
} catch (Exception e) {
// TODO: handle exception
e.printStackTrace();
return null;
}finally{
this.close();
}
return list;
}
//关闭资源
public void close(){
try {
if(rs!=null)
rs.close();
if(pstmt!=null)
pstmt.close();
if(conn!=null)
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
GuiUser实体类
package com.frame;
public class GuiUser {
private String name;
private String password;
publi