JDBC experiment

1. Addition, deletion and modification of JDBC single table records
Known : create a table student, and insert several records into the table,

create table student(

id int PRIMARY KEY auto_increment,

name varchar(20) not null,

schoolin date not null,

score float not null);

insert into student values(null,'Li Li','2015-09-01',86);

insert into student values(null,'Wang Wu','2016-09-01',99);

insert into student values(null,'Zhang San','2014-09-01',88);

Requirements: Use JAVA program to achieve the following functions:

1. Add records to the table and display all records (data specified by yourself);

2. Delete the record with id=1 from the table and display all records;

3. Modify the records in the table: query condition id=2, modify the name to: Shandong University of Technology, and display all records after modification;

4. Query the record with id=3 in the table and display it;


1. Add records to the table and display all records (data specified by yourself)

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

public class Main {
 public static void main(String[] args) throws ClassNotFoundException, SQLException  {
  // 1 加载驱动
  Class.forName("com.mysql.jdbc.Driver");
  // 2 获得数据库的连接
  Connection con =
    DriverManager.getConnection
    ("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8", "root", "");
     //System.out.println(con);

  // insert
  String insertSQL="insert into student values(null,?,?)";
  PreparedStatement pst1 = con.prepareStatement(insertSQL);
  pst1.setString(1,"李四");
  pst1.setInt(2, 25);

  int result=pst1.executeUpdate();
  if(result==1)
  {
   System.out.println("插入记录成功!");
  }
  //查询
  ResultSet rs = pst.executeQuery();
  while(rs.next())
  {
   int id=rs.getInt(1);
   String name=rs.getString(2);
   int age=rs.getInt(3);
   System.out.println(id+"--"+name+"--"+age);
  }

  //7 关闭资源,关闭连接
  pst3.close();

  rs.close();
  pst.close();
  con.close();
 }
}

2. Delete the record with id=1 from the table and display all records;

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

public class Main {
 public static void main(String[] args) throws ClassNotFoundException, SQLException  {
  // 1 加载驱动
  Class.forName("com.mysql.jdbc.Driver");
  // 2 获得数据库的连接
  Connection con =
    DriverManager.getConnection
    ("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8", "root", "");
     //System.out.println(con);

  // delete
  String deleteSQL="delete from student where id=?";
  PreparedStatement pst2 = con.prepareStatement(deleteSQL);
  pst2.setInt(1, 1);

  int result1=pst2.executeUpdate();
  if(result1==1)
  {
   System.out.println("删除记录成功!");
  }
  //6 查询
  ResultSet rs = pst.executeQuery();
  while(rs.next())
  {
   int id=rs.getInt(1);
   String name=rs.getString(2);
   int age=rs.getInt(3);
   System.out.println(id+"--"+name+"--"+age);
  }

  //7 关闭资源,关闭连接
  pst3.close();

  rs.close();
  pst.close();
  con.close();
 }
}

3. Modify the records in the table: query condition id=2, modify the name to: Shandong University of Technology, and display all records after modification;

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

public class Main {
 public static void main(String[] args) throws ClassNotFoundException, SQLException  {
  // 1 加载驱动
  Class.forName("com.mysql.jdbc.Driver");
  // 2 获得数据库的连接
  Connection con =
    DriverManager.getConnection
    ("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8", "root", "");
     //System.out.println(con);

  //5 update
  String updateSQL="update student set name=? where id=?";
  PreparedStatement pst3 = con.prepareStatement(updateSQL);
  pst3.setString(1,"山东理工");
  pst3.setInt(2, 2);//id为2.where后面是条件

  int result=pst3.executeUpdate();
  if(result==1)
  {
   System.out.println("修改记录成功!");
  }
  String sql="select * from student";
  PreparedStatement pst = con.prepareStatement(sql);

  //6 查询
  ResultSet rs = pst.executeQuery();
  while(rs.next())
  {
   int id=rs.getInt(1);
   String name=rs.getString(2);
   int age=rs.getInt(3);
   System.out.println(id+"--"+name+"--"+age);
  }

  //7 关闭资源,关闭连接
  pst3.close();

  rs.close();
  pst.close();
  con.close();
 }
}

4. Query the record with id=3 in the table and display it;

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

public class Main {
 public static void main(String[] args) throws ClassNotFoundException, SQLException  {
  // 1 加载驱动
  Class.forName("com.mysql.jdbc.Driver");
  // 2 获得数据库的连接
  Connection con =
    DriverManager.getConnection
    ("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8", "root", "");
     //System.out.println(con);


//根据主键(id)来查询记录
        String sql = "select * from student where id = ?";
        pst = con.prepareStatement(sql);

        ResultSet rs = pst.executeQuery();
        pst.setInt(1, 3);//id为3

        //查到或者没查到
        Student stu = null;

        if(rs.next()){
            stu = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3));
        }

  //7 关闭资源,关闭连接
  pst3.close();

  rs.close();
  pst.close();
  con.close();
 }
}

Second, JDBC object-oriented way to achieve database CRUD operations. (30 points)

Known: Create a table student and insert several records into the table.

create table student(

id int PRIMARY KEY auto_increment,

name varchar(20) not null,

schoolin date not null,

score float not null);

insert into student values(null,'Li Li','2015-09-01',86);

insert into student values(null,'Wang Wu','2016-09-01',99);

insert into student values(null,'Zhang San','2014-09-01',88);

Basic requirements: Encapsulate table operations into classes, and encapsulate functions into class methods.

Functional requirements:

(1) Add records to the table and display all records (data specified by yourself);

(2) Delete the record with id=1 from the table and display all records;

(3) Modify the records in the table: query condition id=2, modify the name to: Shandong University of Technology, and display all records after modification;

(4) Query the record with id=3 in the table and display it.

Student class: Student.java

public class Student {

    private int id;
    private String name;
    private int age;

    public Student(int id, String name, int age) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
    }

    public Student() {
        super();
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + "]";
    }

    //因为三个属性是私有的,所有可以通过get和set方法取值,赋值
    //变量设置成私有的,方法设置成公开的!-----类的封装
    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;
    }


}

1. Add records to the table and display all records (data specified by yourself);
Student table operation class: StudentDao.java

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


public class StudentDao {

    Connection con;
    PreparedStatement pst;

    public Connection getConn() throws SQLException, ClassNotFoundException{
         //1加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2获得数据库的连接
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8", "root", "");//协议+数据库+端口号+数据库名---------用户名--------密码为空

        return con;
    }

    //增
    public int addStudent(Student student) throws ClassNotFoundException, SQLException{
        con = getConn();
        String insertSQL = "insert into student values(null, ?, ?)";//准备sql语句
        pst = con.prepareStatement(insertSQL);//准备sql语句的对象
        //给?赋值
        pst.setString(1, student.getName());
        pst.setInt(2, student.getAge());

        int result = pst.executeUpdate();

        pst.close();
        con.close();
        return result;

    }
//查询所有记录
    public List<Student> queryAll() throws ClassNotFoundException, SQLException{

        con = getConn();
        String sql = "select * from student";
        pst = con.prepareStatement(sql);

        rs = pst.executeQuery();

        List<Student> list = new ArrayList<Student>();//创建链表容器来存放数据

        while(rs.next()) {

            /*int id = rs.getInt(1);//列是从1开始的
            String name = rs.getString(2);
            int age = rs.getInt(3);
            Student stu = new Student(id, name, age);*/

//            Student stu = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3));

            Student stu = new Student();
            stu.setId(rs.getInt(1));
            stu.setName(rs.getString(2));
            stu.setAge(rs.getInt(3));

            list.add(stu);
        }


        return list;
    }

Test class: Main.java

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

public class Main {
 public static void main(String[] args) throws ClassNotFoundException, SQLException  {
  StudentDao dao=new StudentDao();

  Student stu1=new Student(1,"系统",22);
  int result = dao.addStudent(stu1);
  if(result==1)
  {
   System.out.println("插入记录成功!");
  }
  //显示所有记录
  List<Student> stuList=dao.queryAll();
  for(Student stu:stuList)
  {
   System.out.println(stu);
  }
  System.out.println("=======");
 }
}

2. Delete the record with id=1 from the table and display all records;

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


public class StudentDao {

    Connection con;
    PreparedStatement pst;

    public Connection getConn() throws SQLException, ClassNotFoundException{
         //1加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2获得数据库的连接
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8", "root", "");//协议+数据库+端口号+数据库名---------用户名--------密码为空

        return con;
    }

    //删
    public int deleteStudent(int id) throws ClassNotFoundException, SQLException{
        con = getConn();
        String sql = "delete from student where id=?";//准备sql语句
        pst = con.prepareStatement(sql);//准备sql语句的对象
        //给?赋值
        pst.setInt(1, 1);//删除的条件是id=1

        int result = pst.executeUpdate();

        pst.close();
        con.close();
        return result;

    }

    //查询所有记录
    public List<Student> queryAll() throws ClassNotFoundException, SQLException{

        con = getConn();
        String sql = "select * from student";
        pst = con.prepareStatement(sql);

        rs = pst.executeQuery();

        List<Student> list = new ArrayList<Student>();//创建链表容器来存放数据

        while(rs.next()) {

            /*int id = rs.getInt(1);//列是从1开始的
            String name = rs.getString(2);
            int age = rs.getInt(3);
            Student stu = new Student(id, name, age);*/

//            Student stu = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3));

            Student stu = new Student();
            stu.setId(rs.getInt(1));
            stu.setName(rs.getString(2));
            stu.setAge(rs.getInt(3));

            list.add(stu);
        }


        return list;
    }
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class Main {
 public static void main(String[] args) throws ClassNotFoundException, SQLException  {
  StudentDao dao=new StudentDao();

 int result2 = dao.delStudent(1);
  if(result2==1)
  {
   System.out.println("删除记录成功!");
  }

  List<Student> stuList=dao.queryAll();
  for(Student stu:stuList)
  {
   System.out.println(stu);
  }
  System.out.println("=======");

 }
}

3. Modify the records in the table: query condition id=2, modify the name to: Shandong University of Technology, and display all records after modification;

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


public class StudentDao {

    Connection con;
    PreparedStatement pst;

    public Connection getConn() throws SQLException, ClassNotFoundException{
         //1加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2获得数据库的连接
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8", "root", "");//协议+数据库+端口号+数据库名---------用户名--------密码为空

        return con;
    }

    //改
    public int updateStudent() throws ClassNotFoundException, SQLException{
        con = getConn();
        String sql = "update student set name = ? where id = ?";//准备sql语句
        pst = con.prepareStatement(sql);//准备sql语句的对象
        //给?赋值
        pst.setString(1, "山东理工");
        pst.setInt(2, 2);//修改id为2的name

        int result = pst.executeUpdate();

        pst.close();
        con.close();
        return result;

    }


    //查询所有记录
    public List<Student> queryAll() throws ClassNotFoundException, SQLException{

        con = getConn();
        String sql = "select * from student";
        pst = con.prepareStatement(sql);

        rs = pst.executeQuery();

        List<Student> list = new ArrayList<Student>();//创建链表容器来存放数据

        while(rs.next()) {

            /*int id = rs.getInt(1);//列是从1开始的
            String name = rs.getString(2);
            int age = rs.getInt(3);
            Student stu = new Student(id, name, age);*/

//            Student stu = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3));

            Student stu = new Student();
            stu.setId(rs.getInt(1));
            stu.setName(rs.getString(2));
            stu.setAge(rs.getInt(3));

            list.add(stu);
        }


        return list;
    }
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class Main {
 public static void main(String[] args) throws ClassNotFoundException, SQLException  {
  StudentDao dao=new StudentDao();

  int result3 = dao.updateStudent();
  if(result3==1)
  {
   System.out.println("修改记录成功!");
  }

  List<Student> stuList=dao.queryAll();
  for(Student stu:stuList)
  {
   System.out.println(stu);
  }
  System.out.println("=======");

 }
}

4. Query the record with id=3 in the table and display it.

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


public class StudentDao {

    Connection con;
    PreparedStatement pst;

    public Connection getConn() throws SQLException, ClassNotFoundException{
         //1加载驱动
        Class.forName("com.mysql.jdbc.Driver");
        //2获得数据库的连接
        Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/school?useUnicode=true&characterEncoding=utf-8", "root", "");//协议+数据库+端口号+数据库名---------用户名--------密码为空

        return con;
    }

    //根据主键查询记录
    public Student queryById(int id) throws ClassNotFoundException, SQLException{
        con = getConn();
        String sql = "select * from student where id = ?";
        pst = con.prepareStatement(sql);

        ResultSet rs = pst.executeQuery();
        pst.setInt(1, 3);//查询id为3的记录

        //查到或者没查到
        Student stu = null;

        if(rs.next()){
            stu = new Student(rs.getInt(1), rs.getString(2), rs.getInt(3));

        }

        return stu;
    }
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List;

public class Main {
 public static void main(String[] args) throws ClassNotFoundException, SQLException  {
  StudentDao dao=new StudentDao();

  List<Student> stuList=dao.queryAll();
  for(Student stu:stuList)
  {
   System.out.println(stu);
  }
  System.out.println("=======");

 }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325708150&siteId=291194637