黑马程序员技术交流社区
标题: 【石家庄校区】笔记 [打印本页]
作者: 庞帅 时间: 2018-5-9 17:09
标题: 【石家庄校区】笔记
多表设计之外键约束
1.约束的作用 约束是用来保证数据的完整性。
2.多表约束 外键约束:用来保证数据完整性(多表之间)。
向员工表中插入一条记录(没有部门)
insert into employee values (null,'田八',10000,'1988-09-01','男',null);
删除一个人事部
delete from dept where did = 2;
向刚才做的这两个操作(插入一个没有部门的员工,删除一个带有员工的部门)。这种情况都是不应该发生。这个时候需要在多表之间添加外键约束。
3.在员工表上添加外键 alter table employee add foreign key (dno) references dept(did);
4.设置外键为非空 alter table employee modify dno int not null;
5.一对多关系 在多的一方创建外键指向一的一方的主键
6.多对多的关系 一个学生选择多门课程,一门课程被多个学生所选择
需要创建中间表,中间表中至少两个字段,分别作为外键指向多对多双方的主键
7.多表查询之交叉连接 使用cross join关键字 select * from classes cross join student;
不使用cross join关键字 SELECT * FROM classes,student;
JDBC1.JDBC的工具类的抽取因为传统JDBC的开发,注册驱动,获得连接,释放资源这些代码都是重复编写的。所以可以将重复的代码提取到一个类中来完成。
/**
* JDBC的工具类
* @author jt
*
*/
public class JDBCUtils {
private static final String driverClassName;
private static final String url;
private static final String username;
private static final String password;
static{
driverClassName="com.mysql.jdbc.Driver";
url="jdbc:mysql:///web_test3";
username="root";
password="abc";
}
/**
* 注册驱动的方法
*/
public static void loadDriver(){
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获得连接的方法
*/
public static Connection getConnection(){
Connection conn = null;
try{
// 将驱动一并注册:
loadDriver();
// 获得连接
conn = DriverManager.getConnection(url,username, password);
}catch(Exception e){
e.printStackTrace();
}
return conn;
}
/**
* 释放资源的方法
*/
public static void release(Statement stmt,Connection conn){
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
public static void release(ResultSet rs,Statement stmt,Connection conn){
// 资源释放:
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
rs = null;
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
stmt = null;
}
if(conn != null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
conn = null;
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) |
黑马程序员IT技术论坛 X3.2 |