WEB_09【MySQL多表&JDBC】

特此说明:本文参考黑马程序员视频讲座
@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@
用到的代码准备好:

1.分类表
create table category(
    cid varchar(32) primary key,
    cname varchar(100)
);

2.商品表
create table product(
    pid varchar(32) primary key,
    pname varchar(40),
    price double,
    category_id varchar(32)
);

alter table product add foreign key(category_id) references category(cid);


3.添加外键列
alter table product add category_id varchar(32);

4.添加约束
alter table product add constraint product_fk foreign key(category_id) references category(cid);

5.订单表
create table orders(
    oid varchar(50) primary key,
    totalprice double
);

6.订单项表
create table orderitem(
    oid varchar(50),
    pid varchar(50)
);

7.联合主键
alter table orderitem add primary key(oid,pid);

8.订单表和订单项表的主外键关系
alter table orderitem add constraint orderitem_orders_fk foreign key(oid) references orders(oid);

9.商品表和订单项表的主外键关系
alter table orderitem add constraint orderitem_product_fk foreign key(pid) references product(pid);



insert into category(cid,cname) values('c001','家电');
insert into category(cid,cname) values('c002','服饰');
insert into category(cid,cname) values('c003','化妆品');

insert into product(pid,pname,price,category_id) values('p001','联想','5000','c001');
insert into product(pid,pname,price,category_id) values('p002','海尔','5000','c001');
insert into product(pid,pname,price,category_id) values('p003','雷神','5000','c001');

insert into product(pid,pname,price,category_id) values('p004','JACK JONES','800','c002');
insert into product(pid,pname,price,category_id) values('p005','真维斯','200','c002');
insert into product(pid,pname,price,category_id) values('p006','花花公子','440','c002');
insert into product(pid,pname,price,category_id) values('p007','劲霸','2000','c002');

insert into product(pid,pname,price,category_id) values('p008','香奈儿','800','c003');
insert into product(pid,pname,price,category_id) values('p009','相宜本草','200','c003');

一对多

准备数据库及商品分类表和商品表
这里写图片描述

create table category(
    cid varchar(32) primary key,
    cname varchar(100)
);
``
create table product(
    pid varchar(32) primary key,
    pname varchar(40),
    price double,
    category_id varchar(32)
);
`

添加外键

alter table product add constraint product_fk foreign key(category_id) references category(cid);

添加外键可以是这样:alter table product add foreign key(category_id) references category(cid);但这样的话,不能解除这个外键(除非把从表中引用过主表中的记录删除,才能删除主表中相应的记录),要想解除外键,要增加约束,即按照上面添加外键的方式。

解除外键方法:

alter table product drop foreign key product_fk;

多对多

通过中间表来建立外键
这里写图片描述

alter table table_student add constraint table_student_fk foreign key(student_id) references table_student_course(student_id);

alter table table_course add constraint table_course_fk foreign key(course_id) references table_student_course(course_id);

下面是本讲的例子:

这里写图片描述
上面已经建立好了两个表category和product,现在建立orders和orderitem


create table orders(
    oid varchar(32) primary key,
    totalprice double
);


create table orderitem(
    oid varchar(50),
    pid varchar(50)
);

设置外键:

alter table orderitem add constraint orderitem_orders_fk foreign key(oid) references orders(oid);


alter table orderitem add constraint orderitem_product_fk foreign key(pid) references product(pid);

多表查询及子查询

先插入两条数据
这里写图片描述
自然连接(内连接,交集,inner可以省略)
这里写图片描述
外连接(左外连接,右外连接,outer可以省略)
这里写图片描述
子查询
这里写图片描述

JDBC工具类抽取

这里写图片描述
每次进行数据库查询操作都要注册驱动,获取连接,释放资源,可以把这些抽取成一个工具类,方便每次操作数据库的时候直接调用工具类里面的方法。

工具类JDBCUtils_V1.java

package cn.jdbc;

import static org.junit.Assert.assertNotNull;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/*
 * 提供获取连接和释放资源的方法
 */


public class JDBCUtils_V1 {

    public static Connection getConnection() {
        Connection connection=null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/web_08?","root","123");
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return connection;
    }

    public static void release(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet) {
        if(resultSet!=null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(preparedStatement!=null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
        if(connection!=null) {
            try {
                connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    }
}

这里写图片描述

Junit测试查询:TestUtils.java

package cn.jdbc.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.print.attribute.standard.PresentationDirection;

import org.junit.Test;

import cn.jdbc.JDBCUtils_V1;

/*
 * 测试工具类
 */

public class TestUtils {
    /*
     * 根据id查询用户信息
     */
    @Test
    public void testFindUserById() {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            //1.获取连接
            connection=JDBCUtils_V1.getConnection();
            //2.写SQL
            String sql="select * from table_user where user_id=?";
            //3.获取执行sql语句对象
            preparedStatement=connection.prepareStatement(sql);
            //4.设置参数
            preparedStatement.setInt(1, 2);
            //5。执行查询
            resultSet=preparedStatement.executeQuery();
            //6.处理结果
            while(resultSet.next()) {
                System.out.println(resultSet.getString(2)+"----"+resultSet.getString(3));
            }
            //释放资源不能写在此处,因为万一上面代码执行出错,资源无法释放,占用资源。
        }catch (SQLException e) {
            e.printStackTrace();
            // TODO: handle exception
        }finally {
            //7.释放资源
            JDBCUtils_V1.release(connection, preparedStatement, resultSet);
        }
    }
}

这里写图片描述
发现有红色提示,可以在获取连接的时候加上&useSSL=true,即写成这样就好了:

connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/web_08?&useSSL=true","root","123");

使用properties配置文件并用ResourceBundle对象加载配置文件中的value

开发中获得连接的四个参数(驱动,URL,用户名,密码)通常放在配置文件中,方便后期维护。比如如果需要更换数据库,只需要修改配置文件即可。
1.文件位置任意,建议在src下
2.扩展名:.properties
3.一行一组数据,格式为key=value。value不支持中文,如果需要使用非英文字符,将进行Unicode转换。注意一定不要写多余的空格

这里写图片描述

工具类JDBCUtils_V2.java

package cn.jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ResourceBundle;

/**
 * 利用properties文件提供获取连接和释放资源的方法
 */
public class JDBCUtils_V2 {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    /**
     * 静态代码块加载配置文件信息
     */
    static{
        ResourceBundle bundle = ResourceBundle.getBundle("db");//注意这里没有扩展名
        driver = bundle.getString("driver");
        url = bundle.getString("url");
        username = bundle.getString("username");
        password = bundle.getString("password");
    }

    /**
     * 获取连接方法
     * 
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

测试工具类(TestUtils.java)(除了查询,还有添加操作)

package cn.jdbc.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.print.attribute.standard.PresentationDirection;

import org.junit.Test;

import cn.jdbc.JDBCUtils_V1;
import cn.jdbc.JDBCUtils_V2;

/*
 * 测试工具类
 */

public class TestUtils {
    /*
     * 根据id查询用户信息
     */
    @Test
    public void testFindUserById() {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            //1.获取连接
            connection=JDBCUtils_V1.getConnection();
            //2.写SQL
            String sql="select * from table_user where user_id=?";
            //3.获取执行sql语句对象
            preparedStatement=connection.prepareStatement(sql);
            //4.设置参数
            preparedStatement.setInt(1, 2);
            //5。执行查询
            resultSet=preparedStatement.executeQuery();
            //6.处理结果
            while(resultSet.next()) {
                System.out.println(resultSet.getString(2)+"----"+resultSet.getString(3));
            }
            //释放资源不能写在此处,因为万一上面代码执行出错,资源无法释放,占用资源。
        }catch (SQLException e) {
            e.printStackTrace();
            // TODO: handle exception
        }finally {
            //7.释放资源
            JDBCUtils_V1.release(connection, preparedStatement, resultSet);
        }
    }


    /**
     * 添加用户信息方法
     */
    @Test
    public void testAdd() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 1.获取连接
            conn = JDBCUtils_V2.getConnection();
            // 2.编写sql语句
            String sql = "insert into table_user values(null,?,?)";
            // 3.获取执行sql语句对象
            pstmt = conn.prepareStatement(sql);
            // 4.设置参数
            pstmt.setString(1, "lisi");
            pstmt.setString(2, "hehe");
            // 5.执行插入操作
            int row = pstmt.executeUpdate();
            if (row > 0) {
                System.out.println("添加成功!");
            } else {
                System.out.println("添加失败!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 6.释放资源
            JDBCUtils_V2.release(conn, pstmt, null);
        }
    }
}

使用properties配置文件并用Properties对象加载配置文件中的value

这里写图片描述

工具类JDBCUtils_V3.java

package cn.jdbc;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;
import java.util.ResourceBundle;

/**
 * 提供获取连接和释放资源的 方法
 * 
 * @author Never Say Never
 * @date 2016年7月29日
 * @version V1.0
 */
public class JDBCUtils_V3 {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    /**
     * 静态代码块加载配置文件信息
     */
    static {
        try {
            // 1.通过当前类获取类加载器
            ClassLoader classLoader = JDBCUtils_V3.class.getClassLoader();
            // 2.通过类加载器的方法获得一个输入流
            InputStream is = classLoader.getResourceAsStream("db.properties");
            // 3.创建一个properties对象
            Properties props = new Properties();
            // 4.加载输入流
            props.load(is);
            // 5.获取相关参数的值
            driver = props.getProperty("driver");
            url = props.getProperty("url");
            username = props.getProperty("username");
            password = props.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取连接方法
     * 
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}

测试工具类:TestUtils.java(除查询,添加,还有删除和更新)

package cn.jdbc.test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.print.attribute.standard.PresentationDirection;

import org.junit.Test;

import cn.jdbc.JDBCUtils_V1;
import cn.jdbc.JDBCUtils_V2;
import cn.jdbc.JDBCUtils_V3;

/*
 * 测试工具类
 */

public class TestUtils {
    /*
     * 根据id查询用户信息
     */
    @Test
    public void testFindUserById() {
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;
        try {
            //1.获取连接
            connection=JDBCUtils_V1.getConnection();
            //2.写SQL
            String sql="select * from table_user where user_id=?";
            //3.获取执行sql语句对象
            preparedStatement=connection.prepareStatement(sql);
            //4.设置参数
            preparedStatement.setInt(1, 2);
            //5。执行查询
            resultSet=preparedStatement.executeQuery();
            //6.处理结果
            while(resultSet.next()) {
                System.out.println(resultSet.getString(2)+"----"+resultSet.getString(3));
            }
            //释放资源不能写在此处,因为万一上面代码执行出错,资源无法释放,占用资源。
        }catch (SQLException e) {
            e.printStackTrace();
            // TODO: handle exception
        }finally {
            //7.释放资源
            JDBCUtils_V1.release(connection, preparedStatement, resultSet);
        }
    }


    /**
     * 添加用户信息方法
     */
    @Test
    public void testAdd() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 1.获取连接
            conn = JDBCUtils_V2.getConnection();
            // 2.编写sql语句
            String sql = "insert into table_user values(null,?,?)";
            // 3.获取执行sql语句对象
            pstmt = conn.prepareStatement(sql);
            // 4.设置参数
            pstmt.setString(1, "lisi");
            pstmt.setString(2, "hehe");
            // 5.执行插入操作
            int row = pstmt.executeUpdate();
            if (row > 0) {
                System.out.println("添加成功!");
            } else {
                System.out.println("添加失败!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 6.释放资源
            JDBCUtils_V2.release(conn, pstmt, null);
        }
    }

    /**
     * 根据id更新用户信息方法
     */
    @Test
    public void testUpdateById() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 1.获取连接
            conn = JDBCUtils_V3.getConnection();
            // 2.编写sql语句
            String sql = "update table_user set user_password=? where user_id=?";
            // 3.获取执行sql语句对象
            pstmt = conn.prepareStatement(sql);
            // 4.设置参数
            pstmt.setString(1, "999");
            pstmt.setInt(2, 3);
            // 5.执行更新操作
            int row = pstmt.executeUpdate();
            if (row > 0) {
                System.out.println("更新成功!");
            } else {
                System.out.println("更新失败!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 6.释放资源
            JDBCUtils_V3.release(conn, pstmt, null);
        }
    }

    /**
     * 根据id删除信息方法
     */
    @Test
    public void testDeleteById() {
        Connection conn = null;
        PreparedStatement pstmt = null;
        try {
            // 1.获取连接
            conn = JDBCUtils_V3.getConnection();
            // 2.编写sql语句
            String sql = "delete from table_user where user_id=?";
            // 3.获取执行sql语句对象
            pstmt = conn.prepareStatement(sql);
            // 4.设置参数
            pstmt.setInt(1, 4);
            // 5.执行删除操作
            int row = pstmt.executeUpdate();
            if (row > 0) {
                System.out.println("删除成功!");
            } else {
                System.out.println("删除失败!");
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        } finally {
            // 6.释放资源
            JDBCUtils_V3.release(conn, pstmt, null);
        }
    }


}

猜你喜欢

转载自blog.csdn.net/ccnuacmhdu/article/details/80367060