编程顺序:
对象—>dao层—>view层
一、对象 :
面向对象的思想添加属性
数据库显示数字为空时定义为Integer
set,get方法自动生成,属性加private
二、dao层:
增 删 改 查
给方法传数据最好穿对象当数据的载体
经常连接数据库可以封装成一个单独的方法
Connection 连接 prepare 准备
导包的时候导sql包不要mysql
链接数据库七步
1.在项目上导入对应的数据库jar包
2.利用反射,加载数据库驱动
Class.forName(“com.mysql.jdbc.Driver”);
3.建立连接
Connection conn=DriverManager.getConnection(“jdbc:mysql://localhost:3306/company”,”root”,”root”);
建立statement sql语句执行器
//事务 conn.setAuttoCommit(flas) sql语句默认提交 改成手动提交
Statement stat=conn.createStatement();
5.执行sql语句得到结果ResultSet rs=stat.executeQuery(“select * from empolyee”);
int rs =stat.executeUpdate(sql)
conn.commit(); 手动提交sql语句
查询用 executeQuery 增删改用executeUpdate返回int 修改的条数
6.对得到的结果进行操作
while(rs.next()) {
System.out.print(rs.getInt(“id”)+”“);
System.out.print(rs.getString(“name”)+”“);
System.out.print(rs.getString(“sex”)+”“);
System.out.print(rs.getInt(“age”));
System.out.println();
}
7.关闭
rs.close();
stat.close();
conn.close();
编码格式
characterEconding=utf-8
characterEncoding=gb2312
当有多条sql语句需要统一执行后才可以的时候添加事务
conn. conn.setAuttoCommit(false)把提交方式改为手动提交
conn.commit(); 提交sql语句
rs.next()遍历整个rs,默认的时第一条的前一行
String 转换int
String str = null;
int age = -1;
if (!(str.equals(“”) || str == null)) {
age = Integer.parseInt(“str”);
selsct筛选条件模式
判断传过来的数据是不是符合条件
if((e.name.equals(name)||name.equals(“”))&&
(e.sex.equals(sex)||sex.equals(“”))&&
(e.age==age||age==-1)){
}根据判断添加sql语句的where条件where 1=1 设置为第一个条件防止and前没有条件
String where = ” where 1=1”;
if (!score.getEmployee().getName().equals(“”)) {
where += ” and e.name like ‘%” + score.getEmployee().getName() + “%’”;
}
if (!score.getEmployee().getSex().equals(“无”)) {
where += ” and e.sex=’”+ score.getEmployee().getSex()+”’”;
}
if (score.getEmployee().getAge() != -1) {
where += ” and e.age like ‘” + score.getEmployee().getAge() + “%’”;
}
3.使用prepareStatement方法,拼接sql语句
PreparedStatement preStat = null;
String sql = “select * from department where id=? or name=?”;
preStat = conn.prepareStatement(sql);
preStat.setInt(1, 1);
preStat.setString(2, “测试部”);
ResultSet rs = preStat.executeQuery();
rs.close();
preStat.close();
conn.close();
增删改用executeUpdate 返回 int 修改的行数
搜索用 executeQuery
三、view层
java.swing包
新版 控件前有 j 区分
窗口——>面板——>控件
布局 方法
主面板从窗口中获取
默认的布局时流式布局
窗口最后设置显示
例如添加和修改这种很像的窗口可以建一个父类继承下来
要实现只有一个窗口要借用但单例模式,私有的构造函数,对外开放一个实现方法
table需要放到JScrollPane滚动面板中
table各种属性可以建一个model继承AbstractTableModel
控件刷新用 .updateUi()
其他层不应该有权限刷新view界面,可以建一个CallBack接口,实现这个接口通知view刷新界面