Java(三)JDBC与数据库操作

JDBC与数据库操作

目录

JDBC与数据库操作

练习一: 掌握JDBC连接MySQL和SQL Server的方法,并撰写实例

JDBC连接MySQL的方法及实例

JDBC连接SQL Server的方法及实例

练习二: 利用prop文件的读写,实现数据库连接参数的可配置

练习三: 通过JDBC对MySQL数据库进行增删改查操作,熟悉基本的CRUD

设计数据库表

定义实体类

定义数据库连接

实现数据库的增删改查

查询

增加

删除

更新

练习四: 按照上一实验Item、CartItem、Cart三个类的属性,设计MySQL数据库order     的三张表items、cartitems、carts

表items

表cartitems

表carts

练习五: 了解DAO设计范式,为Item、CartItem、Cart三个类分别设计DAO

DAO设计范式-Item

DAO设计范式- CartItem

DAO设计范式- Cart

总结:

拓展:SQL Server触发器实现多表之间同步增加、删除与更新


练习一: 掌握JDBC连接MySQL和SQL Server的方法,并撰写实例

  1. JDBC连接MySQL的方法及实例

 

运行结果:

 

代码如下:

package myThirdJavaPractice;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;



public class Practice1 {

    public static void main(String[] args)

    {

        try

        {

            // 之所以要使用下面这条语句,是因为要使用MySQL的驱动,所以我们要把它驱动起来,

            // 可以通过Class.forName把它加载进去,也可以通过初始化来驱动起来

            // 第一步:注册驱动

            Class.forName("com.mysql.cj.jdbc.Driver");// 动态加载mysql驱动

            // 建立连接

           // 一个Connection代表一个数据库连接

            Connection conn = DriverManager.getConnection(

                    "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC", "root", "970000");

            // Statement接口用来处理发送到数据库的SQL语句对象

            // 1.execute方法,如果执行的sql是查询语句且有结果集则返回true,如果是非查询语句或者没有结果集,返回false

            // 2.executeQuery方法,执行查询语句,返回结果集

            // 3.executeUpdate方法,执行DML(update/delete/insert)语句,返回影响的记录数

            Statement stmt = conn.createStatement();

            String sql = "select * from MyClass";

            if (stmt.execute(sql))

            {

                System.out.println("有数据");

            } else

            {

                System.out.println("无数据");

            }

            // ResultSet接口用来执行查询SQL语句后返回的结果

            ResultSet rs = stmt.executeQuery(sql);

            // 遍历返回的结果集

            while (rs.next())

            {

                String name = rs.getString("name");

                System.out.println("name is:" + name);

                String id = rs.getString("id");

                System.out.println("id is:" + id);

            }

            System.out.println(stmt.executeUpdate("update MyClass set name = '邬必芬' where id = 2"));

            rs.close();

            stmt.close();

            conn.close();

        } catch (ClassNotFoundException e)

        {

            e.printStackTrace();

        } catch (SQLException e)

        {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

}
  1. JDBC连接SQL Server的方法及实例

 

 

SQL Server新建数据库新建表,并插入数据

 

运行结果:

 

代码如下:

package myThirdJavaPractice;



import java.sql.*;



public class Practice12 {

     public static void main(String[] arg){ 

            PreparedStatement ps=null; 

            Connection ct=null; 

            ResultSet rs=null; 

        try { 

            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); 

            ct=DriverManager.getConnection 

            ("jdbc:sqlserver://127.0.0.1:1433;DatabaseName=mydatabase","sa","970000"); 

            ps=ct.prepareStatement("select * from mystudent"); 

            rs=ps.executeQuery(); 

            while(rs.next()){ 

                String s=rs.getString(2); 

                System.out.println(s); 

            } 

             

        } catch (Exception e) { 

            e.printStackTrace(); 

            // TODO: handle exception 

        }    

                 

             

        } 

}

 

 

练习二: 利用prop文件的读写,实现数据库连接参数的可配置

  1. 目录如下:

 

 

  1. Practice2.java
package myThirdJavaPractice;



    import java.io.InputStream;

    import java.sql.Connection;

    import java.sql.Driver;

    import java.util.Properties;



public class Practice2 {

        public static void main(String[] args) {

           

        }

        public Connection getConnection() throws Exception{

            String driverClass=null;

            String jdbcUrl=null;

            String user=null;

            String pwd=null;

           

            InputStream in=getClass().getClassLoader().getResourceAsStream("config.properties");

            Properties properties=new Properties();

            properties.load(in);

           

            driverClass=properties.getProperty("driver");

            jdbcUrl=properties.getProperty("url");

            user=properties.getProperty("user");

            pwd=properties.getProperty("pwd");

           

            //forName 返回一个类,newInstance创建一个对象

            Driver driver=(Driver) Class.forName(driverClass).newInstance();

            Properties info=new Properties();

            info.put("user",user);

            info.put("password",pwd);

            Connection connection=driver.connect(jdbcUrl, info);

            return connection;

        }

        public void testConnection() throws Exception{

            System.out.println(getConnection());   

        }

}

 

 

 

  1. config.properties
url=jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC

user=root

pwd=970000

driver=com.mysql.cj.jdbc.Driver

  

4、测试结果:

 

 

练习三: 通过JDBC对MySQL数据库进行增删改查操作,熟悉基本的CRUD

  1. 设计数据库表

create table MyStudent

(

id int(4) primary key auto_increment,

name char(20),

age int(4),

sex int(4)

)

 

  1. 定义实体类

代码如下:

package myThirdJavaPractice;



public class Practice3Student{

    private int id; 

    private String name; 

    private int age; 

    private int sex; 

 

    public int getId() { 

        return id; 

    } 

 

    public void setId(int id) { 

        this.id = id; 

    } 

 

    public String getName() { 

        return name; 

    } 

 

    public void setName(String name) { 

        this.name = name; 

    } 

 

    public int getAge() { 

        return age; 

    } 

 

    public void setAge(int age) { 

        this.age = age; 

    } 

 

    public int getSex() { 

        return sex; 

    } 

 

    public void setSex(int sex) { 

        this.sex = sex; 

    } 

 

    public String toString() { 

        return "Student [id=" + id + ", name=" + name + ", age=" + age 

                + ", sex=" + sex  +  "]";

    } 

}

 

  1. 定义数据库连接

运行结果:

 

 

代码如下:

package myThirdJavaPractice;



import java.sql.Connection; 

import java.sql.DriverManager; 



public class Practice3DBUtil {

    public static void main(String args[])

    {

       

            String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";

            String driver = "com.mysql.cj.jdbc.Driver";

            try{

                Class.forName(driver);

            }catch(Exception e){

                System.out.println("无法加载驱动");

            }

           

    try {

            Connection con = DriverManager.getConnection(url,"root","970000");

            if(!con.isClosed())

                System.out.println("success");

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }

    }

}

  1. 实现数据库的增删改查

查询

运行结果:

 

 

增加

1、运行结果:

 

 

2、执行插入后查看数据库也对应有了变化

 

 

3、代码如下:

package myThirdJavaPractice;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;



import myThirdJavaPractice.Practice3StudentDao;

import myThirdJavaPractice.Practice3Student;



public class Practice3StudentDao {

//插入

     public boolean insertStudent(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("insert into mystudent(id,name,sex,age) values (24,'RayMa',1,31)");

            return resRow > 0;

        }

//更新

        public boolean updateStudent(Connection connection, String sql) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement.executeUpdate(sql);

            return resRow > 0;

        }

//查询

        public List<Practice3Student> getStudentList(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            ResultSet resultSet = statement.executeQuery("select * from mystudent");

            List<Practice3Student> students = new ArrayList<>();

            Practice3Student student;

            while (resultSet.next())

            {

               student = new Practice3Student();

               student.setId(resultSet.getInt("id"));

               student.setName(resultSet.getString("name"));

               student.setSex(resultSet.getInt("sex"));

               student.setAge(resultSet.getInt("age"));

               students.add(student);

            }

            return students;

        }

       

//删除

        public boolean deleteStudent(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("delete from mystudent where id in (24) ");

            return resRow > 0;

        }

     

        public static void main(String[] args) throws SQLException

        {

          



           String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";

           String driver = "com.mysql.cj.jdbc.Driver";

           try{

              Class.forName(driver);

           }catch(Exception e){

              System.out.println("无法加载驱动");

           }

              

          

    try {

           Connection connection = DriverManager.getConnection(url,"root","970000");

           if(!connection.isClosed())

              System.out.println("success");

           Practice3StudentDao dao = new Practice3StudentDao();

           dao.insertStudent(connection);

           //dao.deleteStudent(connection);



           List<Practice3Student> students = dao.getStudentList(connection);   

            for( Practice3Student student : students) { 

                System.out.println(student); 

            } 

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }  }

}

 

删除

1、运行结果:

2、执行删除后的数据库截图:

3、代码如下:

package myThirdJavaPractice;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;



import myThirdJavaPractice.Practice3StudentDao;

import myThirdJavaPractice.Practice3Student;



public class Practice3StudentDao {

//插入

     public boolean insertStudent(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("insert into mystudent(id,name,sex,age) values (24,'RayMa',1,31)");

            return resRow > 0;

        }

//更新

        public boolean updateStudent(Connection connection, String sql) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement.executeUpdate(sql);

            return resRow > 0;

        }

//查询

        public List<Practice3Student> getStudentList(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            ResultSet resultSet = statement.executeQuery("select * from mystudent");

            List<Practice3Student> students = new ArrayList<>();

            Practice3Student student;

            while (resultSet.next())

            {

               student = new Practice3Student();

               student.setId(resultSet.getInt("id"));

               student.setName(resultSet.getString("name"));

               student.setSex(resultSet.getInt("sex"));

               student.setAge(resultSet.getInt("age"));

               students.add(student);

            }

            return students;

        }

       

//删除

        public boolean deleteStudent(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("delete from mystudent where id in (24) ");

            return resRow > 0;

        }

     

        public static void main(String[] args) throws SQLException

        {

          



           String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";

           String driver = "com.mysql.cj.jdbc.Driver";

           try{

              Class.forName(driver);

           }catch(Exception e){

              System.out.println("无法加载驱动");

           }

              

          

    try {

           Connection connection = DriverManager.getConnection(url,"root","970000");

           if(!connection.isClosed())

              System.out.println("success");

           Practice3StudentDao dao = new Practice3StudentDao();

           //dao.insertStudent(connection);

           dao.deleteStudent(connection);



           List<Practice3Student> students = dao.getStudentList(connection);   

            for( Practice3Student student : students) { 

                System.out.println(student); 

            } 

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }  }

}

 

 

更新

1、运行结果:

2、执行代码后数据库也发生了相应的变化:

 

3、代码如下:

package myThirdJavaPractice;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;



import myThirdJavaPractice.Practice3StudentDao;

import myThirdJavaPractice.Practice3Student;



public class Practice3StudentDao {

//插入

     public boolean insertStudent(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("insert into mystudent(id,name,sex,age) values (24,'RayMa',1,31)");

            return resRow > 0;

        }

//更新

        public boolean updateStudent(Connection connection, String sql) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement.executeUpdate(sql);

            return resRow > 0;

        }

//查询

        public List<Practice3Student> getStudentList(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            ResultSet resultSet = statement.executeQuery("select * from mystudent");

            List<Practice3Student> students = new ArrayList<>();

            Practice3Student student;

            while (resultSet.next())

            {

               student = new Practice3Student();

               student.setId(resultSet.getInt("id"));

               student.setName(resultSet.getString("name"));

               student.setSex(resultSet.getInt("sex"));

               student.setAge(resultSet.getInt("age"));

               students.add(student);

            }

            return students;

        }

       

//删除

        public boolean deleteStudent(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("delete from mystudent where id in (24) ");

            return resRow > 0;

        }

     

        public static void main(String[] args) throws SQLException

        {

          

            String sql=null;

           String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";

           String driver = "com.mysql.cj.jdbc.Driver";

           try{

              Class.forName(driver);

           }catch(Exception e){

              System.out.println("无法加载驱动");

           }

              

          

    try {

           Connection connection = DriverManager.getConnection(url,"root","970000");

           if(!connection.isClosed())

              System.out.println("success");

           Practice3StudentDao dao = new Practice3StudentDao();

           //dao.insertStudent(connection);

           //dao.deleteStudent(connection);

           dao.updateStudent(connection,"update mystudent set name='二爷'where id in (24)");

           List<Practice3Student> students = dao.getStudentList(connection);   

            for( Practice3Student student : students) { 

                System.out.println(student); 

            } 

       } catch (Exception e) {

           // TODO Auto-generated catch block

           e.printStackTrace();

       }  }

}

 

练习四: 按照上一实验Item、CartItem、Cart三个类的属性,设计MySQL数据库order     的三张表items、cartitems、carts

表items

create table items

(

id int(20) primary key auto_increment,

name char(80) ,

price int(20) ,

description char(160)

)

 

 

 

表cartitems

   create table cartitems

(

id int(20) primary key auto_increment,

name char(80) ,

price int(20) ,

description char(160),

quantity int(20),

Xjprice int(20)

)

 

 

表carts

create table cart

(

id int(20) primary key auto_increment,

name char(80) ,

price int(20) ,

description char(160),

quantity int(20),

Xjprice int(20),

totalprice int(20)

)

   

 

 

 

练习五: 了解DAO设计范式,为Item、CartItem、Cart三个类分别设计DAO

DAO设计范式-Item

 

  1. 查询

运行结果:

 

 

 

  1. 插入

运行结果:

 

 

  1. 删除

运行结果:

 

 

  1. 更新

运行结果:

 

  1. ItemDao代码如下:
package myThirdJavaPractice;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;



import mySecondJavaPractice.Item;



public class ItemDao {

    //插入

         public boolean insertItem(Connection connection) throws SQLException

            {

                Statement statement = connection.createStatement();

                int resRow = statement

                        .executeUpdate("insert into items(id,name,price,description) values (5,'睿智肌极地冰肌',578,'美白保湿套装')");

                return resRow > 0;

            }

    //更新

            public boolean updateItem(Connection connection, String sql) throws SQLException

            {

                Statement statement = connection.createStatement();

                int resRow = statement.executeUpdate(sql);

                return resRow > 0;

            }

    //查询

            public List<Item> getItemList(Connection connection) throws SQLException

            {

                Statement statement = connection.createStatement();

                ResultSet resultSet = statement.executeQuery("select * from items");

                List<Item> items = new ArrayList<>();

                Item item;

                while (resultSet.next())

                {

                item = new Item();

                item.setId(resultSet.getInt("id"));

                item.setName(resultSet.getString("name"));

                item.setPrice(resultSet.getInt("price"));

                item.setDescription(resultSet.getString("description"));

                items.add(item);

                }

                return items;

            }

           

    //删除

            public boolean deleteItem(Connection connection) throws SQLException

            {

                Statement statement = connection.createStatement();

                int resRow = statement

                        .executeUpdate("delete from items where id in (4) ");

                return resRow > 0;

            }

         

            public static void main(String[] args) throws SQLException

            {

           

                String sql=null;

                String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";

                String driver = "com.mysql.cj.jdbc.Driver";

                try{

                    Class.forName(driver);

                }catch(Exception e){

                    System.out.println("无法加载驱动");

                }

                   

               

        try {

                Connection connection = DriverManager.getConnection(url,"root","970000");

                if(!connection.isClosed())

                    System.out.println("success");

                ItemDao dao = new ItemDao();

                //dao.insertItem(connection);

                 //dao.deleteItem(connection);

                dao.updateItem(connection,"update items set price=400 where id in (1)");

                List<Item> items = dao.getItemList(connection);   



                for( Item item : items) { 

                    System.out.println(item); 

                } 

            } catch (Exception e) {

                // TODO Auto-generated catch block

                e.printStackTrace();

            }  }

}

 

 

DAO设计范式- CartItem

  1. 查询

运行结果:

 

  1. 插入

运行结果:

 

数据库对应变化:

 

  1. 删除

运行结果:

  数据库对应变化:

 

 

  1. 更新

运行结果:

数据库对应变化:

 

 

  1. CartItemDao代码如下:
package myThirdJavaPractice;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;



import mySecondJavaPractice.Item;

import mySecondJavaPractice.CartItem;



public class CartItemDao {

    //插入

     public boolean insertCartItem(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("insert into cartitems(id,name,price,description,quantity,Xjprice) values (5,'睿智肌极地冰肌',578,'美白保湿套装',3,1734)");

            return resRow > 0;

        }

//更新

        public boolean updateCartItem(Connection connection, String sql) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement.executeUpdate(sql);

            return resRow > 0;

        }

//查询

        public List<CartItem> getCartItemList(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            ResultSet resultSet = statement.executeQuery("select * from cartitems");

            List<CartItem> cartItems = new ArrayList<>();

            CartItem cartItem;

            while (resultSet.next())

            {

                Item item;

                item = new Item();

            cartItem = new CartItem();

            item.setId(resultSet.getInt("id"));

            item.setName(resultSet.getString("name"));

            item.setPrice(resultSet.getInt("price"));

            item.setDescription(resultSet.getString("description"));

            cartItem=new CartItem(item,resultSet.getInt("quantity"));          

            cartItems.add(cartItem);

            }

            return cartItems;

        }

       

//删除

        public boolean deleteCartItem(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("delete from cartitems where id in (3) ");

            return resRow > 0;

        }

     

        public static void main(String[] args) throws SQLException

        {

       

           String sql=null;

            String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";

            String driver = "com.mysql.cj.jdbc.Driver";

            try{

                Class.forName(driver);

            }catch(Exception e){

                System.out.println("无法加载驱动");

            }

               

           

    try {

            Connection connection = DriverManager.getConnection(url,"root","970000");

            if(!connection.isClosed())

                System.out.println("success");

           

            CartItemDao dao = new CartItemDao();

           

            //dao.insertCartItem(connection);

            //dao.deleteCartItem(connection);

            dao.updateCartItem(connection,"update cartitems set price=500 where id in (4)");

            List<CartItem> cartItems = dao.getCartItemList(connection);   

           

            for( CartItem cartItem : cartItems) { 

               System.out.println(cartItem); 

           } 

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }  }

}

 

DAO设计范式- Cart

  1. 查询

运行后数据库结果:

 

  1. 插入

运行后数据库结果:

 

  1. 删除

运行后数据库结果:

 

  1. 更新

运行后数据库结果:

 

 

  1. CartDao代码如下:
package myThirdJavaPractice;



import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.ArrayList;

import java.util.List;



import mySecondJavaPractice.Cart;

import mySecondJavaPractice.CartItem;

import mySecondJavaPractice.Item;



public class CartDao {

    //插入

     public boolean insertCart(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("insert into cart(id,name,price,description,quantity,Xjprice,totalprice) values (5,'睿智肌极地冰肌',78,'美白保湿套装',1,78,901)");

            return resRow > 0;

        }

//更新

        public boolean updateCart(Connection connection, String sql) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement.executeUpdate(sql);

            return resRow > 0;

        }

//查询

        public List<Cart> getCartList(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            ResultSet resultSet = statement.executeQuery("select * from cart");

            List<Cart> carts = new ArrayList<>();

            Cart cart;

            while (resultSet.next())

            {

                Item item;

                CartItem cartItem;

                item = new Item();

            cartItem = new CartItem();

            item.setId(resultSet.getInt("id"));

            item.setName(resultSet.getString("name"));

             item.setPrice(resultSet.getInt("price"));

            item.setDescription(resultSet.getString("description"));

            cartItem=new CartItem(item,resultSet.getInt("quantity"));

            cart= new Cart(cartItem);

            carts.add(cart);

            }

            return carts;

        }

       

//删除

        public boolean deleteCart(Connection connection) throws SQLException

        {

            Statement statement = connection.createStatement();

            int resRow = statement

                    .executeUpdate("delete from cart where id in (4) ");

            return resRow > 0;

        }

     

        public static void main(String[] args) throws SQLException

        {

       

          String sql=null;

            String url = "jdbc:mysql://127.0.0.1:3306/mydatabase?useUnicode=true&characterEncoding=UTF-8&useSSL=false&serverTimezone=UTC";

            String driver = "com.mysql.cj.jdbc.Driver";

            try{

                Class.forName(driver);

            }catch(Exception e){

                System.out.println("无法加载驱动");

            }

               

           

    try {

            Connection connection = DriverManager.getConnection(url,"root","970000");

            if(!connection.isClosed())

                System.out.println("success");

           

            CartDao dao = new CartDao();

           

            //dao.insertCart(connection);

            //dao.deleteCart(connection);

            dao.updateCart(connection,"update cart set quantity=2 where id in (1)");

            List<Cart> carts = dao.getCartList(connection);   



            for( Cart cart : carts) { 

              System.out.println(cart); 

          } 

        } catch (Exception e) {

            // TODO Auto-generated catch block

            e.printStackTrace();

        }  }

}

总结:

1、通过这次实验,掌握了JDBC连接MySQL和SQL Server的方法,另外还学习了另一种方法就是写配置文件来连接数据库。

2、通过JDBC对MySQL数据库进行增删改查操作,熟悉了基本的CRUD。

3、联系第二次实验,实现了具体的实践操作,了解DAO设计范式。

4、实验出现的问题经过仔细思考、百度查询基本都解决了,也有一些问题待解决。

拓展:SQL Server触发器实现多表之间同步增加、删除与更新

看题目要求是为每个表设计DAO范式,考虑能否用SQL Server触发器(Trigger)实现多表之间同步增加、删除与更新?

代码如下:

--创建items表
create table items
(
id int identity primary key,
name varchar(80),
price int,
description varchar(160)
)
--创建cartitems表
  create table cartitems
(
id int identity primary key ,
name varchar(80) ,
price int,
description varchar(160),
quantity int,
Xjprice int
)
--创建cart表
create table cart
(
id int identity primary key,
name varchar(80) ,
price int ,
description varchar(160),
quantity int,
Xjprice int,
totalprice int
)
--创建INSERT触发器脚本命令
CREATE TRIGGER t_items_insert 
ON items
AFTER INSERT 
AS BEGIN INSERT INTO 
cartitems (name,price,description)
SELECT name,price,description 
FROM INSERTED
END
go
--创建DELETE触发器脚本命令
CREATE TRIGGER t_items_delete 
ON items 
AFTER DELETE 
AS BEGIN DELETE cartitems 
WHERE 
id IN( 
SELECT id
FROM DELETED) 
END
go
--创建UPDATE 触发器脚本命令
CREATE TRIGGER t_items_update   
ON items 
AFTER UPDATE 
AS 
         Update cartitems 
           Set 
           price=i.price 
           From cartitems br , Deleted   d ,Inserted i      --Deleted和Inserted临时表 
           Where br.id=d.id 
--------再建一级触发器---------
--创建INSERT触发器脚本命令
CREATE TRIGGER t_cartitems_insert 
ON cartitems
AFTER INSERT 
AS BEGIN INSERT INTO 
cart (name,price,description)
SELECT name,price,description 
FROM INSERTED
END
go
--创建DELETE触发器脚本命令
CREATE TRIGGER t_cartitems_delete 
ON cartitems 
AFTER DELETE 
AS BEGIN DELETE cart 
WHERE 
id IN( 
SELECT id
FROM DELETED) 
END
go
--创建UPDATE 触发器脚本命令
CREATE TRIGGER t_cartitems_update   
ON items 
AFTER UPDATE 
AS 
         Update cart 
           Set 
           price=i.price 
           From cart br , Deleted   d ,Inserted i      --Deleted和Inserted临时表 
           Where br.id=d.id 
--插入语句,允许将显式值插入表的标识列中 ON-允许  OFF-不允许
set identity_insert items ON
insert into items(id,name,price,description)values(1,'Benifit眉粉',228,'眉粉魔力宝盒套组')
insert into items(id,name,price,description)values(2,'Laura Mercier高光',265,'highlight-01')
insert into items(id,name,price,description)values(3,'空山新雨多功能刷',35,'多功能定妆GP02')
set identity_insert items OFF
--查询语句
select*    from items
select* from cartitems
select* from cart
--删除语句
delete from items where id=3
delete from cartitems where id=4
--删除触发器脚本命令
drop trigger t_items_insert
--删除表语句
drop table items
drop table cartitems
drop table cart
--更新语句
update items SET price='200' WHERE id ='2' 


截图:

 

 

猜你喜欢

转载自blog.csdn.net/RayMa0305/article/details/81214070