JDBC [1]-primary addition, deletion, modification and investigation

[TOC]

1. What is jdbc

  • JDBC(Java DataBase Connectivity, java database connection) is used to execute SQL statements Java API, can provide unified access to a variety of relational databases, it is composed of a set of classes and interfaces written in Java language. JDBCProvides a benchmark from which more advanced tools and interfaces can be built to enable database developers to write database applications. (Baidu Encyclopedia)
  • jdbcIt is often used to connect to the database, create sqlor mysqlstatement, use related apito execute sql statement, so as to operate the database, to achieve the purpose of viewing or modifying the database.
  • Learning jbbc requires a certain understanding of java programming, and an understanding of a database system and sqlstatements.
  • Environmental requirements:
    1. Installed locally jdk, and installed the mysqldatabase, I directly installed the mysql wampwith the mysqldatabase/ dockerinstallation.
    2. Use IDEA to develop

2. Use IDEA to develop

2.1 Create a database, data table

My mysql is created using docker, if it is a windows environment, it is more convenient to use wamp.

The database name is test, and the name of the data table is student. There are four fields in it, one is id, which is the primary key (auto-increment), as well as name, age, and grade. Finally, use the sql statement to insert six test records.

CREATE DATABASE `test` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

USE test;

CREATE TABLE `student` ( `id` INT NOT NULL AUTO_INCREMENT , `name` VARCHAR(20) NOT NULL , 
`age` INT NOT NULL , `score` DOUBLE NOT NULL , PRIMARY KEY (`id`)) ENGINE = MyISAM; 

INSERT INTO `student` VALUES (1, '小红', 26, 83);
INSERT INTO `student` VALUES (2, '小白', 23, 93);
INSERT INTO `student` VALUES (3, '小明', 34, 45);
INSERT INTO `student` VALUES (4, '张三', 12, 78);
INSERT INTO `student` VALUES (5, '李四', 33, 96);
INSERT INTO `student` VALUES (6, '魏红', 23, 46);
2.2 Use IDEA to create a project

I use the maven project method, the project directory:
JDBC [1]-primary addition, deletion, modification and investigation

Student.class

package model;

/**
 * student类,字段包括id,name,age,score
 * 实现无参构造,带参构造,toString方法,以及get,set方法
 */
public class Student {
    private int id;
    private String name;
    private int age;
    private double score;

    public Student() {
        super();
        // TODO Auto-generated constructor stub
    }
    public Student(String name, int age, double score) {
        super();
        this.name = name;
        this.age = age;
        this.score = score;
    }
    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 double getScore() {
        return score;
    }
    public void setScore(double score) {
        this.score = score;
    }
    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age
                + ", score=" + score + "]";
    }

}

DBUtil.class

package db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
/**
 * 工具类,获取数据库的连接
 * @author 秦怀
 *
 */
public class DBUtil {
    private static String URL="jdbc:mysql://127.0.0.1:3306/test?characterEncoding=utf-8&serverTimezone=UTC";
    private static String USER="root";
    private static String PASSWROD ="123456";
    private static Connection connection=null;
    static{
        try {
            Class.forName("com.mysql.jdbc.Driver");
            // 获取数据库连接
            connection=DriverManager.getConnection(URL,USER,PASSWROD);
            System.out.println("连接成功");
        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // 返回数据库连接
    public static Connection getConnection(){
        return connection;
    }
}

StudentDao.class

package dao;

import model.Student;

import java.util.ArrayList;
import java.util.List;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import db.DBUtil;
/**
 * 操作学生表的dao类
 * @author 秦怀
 * 下面均使用预编译的方法
 */
public class StudentDao {
    //将连接定义为单例
    private static Connection connection = DBUtil.getConnection();
    // 添加新的学生
    public void addStudent(Student student){
        String sql ="insert into student(name,age,score) "+
                    "values(?,?,?)";
        boolean result = false;
        try {
            // 将sql传进去预编译
            PreparedStatement preparedstatement = connection.prepareStatement(sql);
            // 下面把参数传进去
            preparedstatement.setString(1, student.getName());
            preparedstatement.setInt(2, student.getAge());
            preparedstatement.setDouble(3, student.getScore());
            preparedstatement.execute();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("创建数据库连接失败");
        }
    }
    // 更新学生信息
    public void updateStudent(Student student){
        String sql = "update student set name = ? ,age =?,score = ? where id = ? ";
        boolean result = false;
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setString(1, student.getName());
            preparedStatement.setInt(2, student.getAge());
            preparedStatement.setDouble(3, student.getScore());
            preparedStatement.setInt(4, student.getId());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("连接数据库失败");
        }
    }
    // 根据id删除一个学生
    public void deleteStudent(int id){
        String sql = "delete from student where id = ?";
        boolean result = false;
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, id);
            result=preparedStatement.execute();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
    // 根据id查询学生
    public Student selectStudent(int id){
        String sql ="select * from student where id =?";
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setInt(1, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            Student student = new Student();
            // 一条也只能使用resultset来接收
            while(resultSet.next()){
                student.setId(resultSet.getInt("id"));
                student.setName(resultSet.getString("name"));
                student.setAge(resultSet.getInt("age"));
                student.setScore(resultSet.getDouble("score"));
            }
            return student;
        } catch (SQLException e) {
            // TODO: handle exception
        }
        return null;
    }
    // 查询所有学生,返回List
    public List<Student> selectStudentList(){
        List<Student>students  = new ArrayList<Student>(); 
        String sql ="select * from student ";
        try {
            PreparedStatement preparedStatement = DBUtil.getConnection().prepareStatement(sql);
            ResultSet resultSet = preparedStatement.executeQuery();
            // 不能把student在循环外面创建,要不list里面六个对象都是一样的,都是最后一个的值,
            // 因为list add进去的都是引用
            // Student student = new Student();
            while(resultSet.next()){
                Student student = new Student();
                student.setId(resultSet.getInt(1));
                student.setName(resultSet.getString(2));
                student.setAge(resultSet.getInt(3));
                student.setScore(resultSet.getDouble(4));
                students.add(student);

            }
        } catch (SQLException e) {
            // TODO: handle exception
        }
        return students;
    }
}

StudentAction.class

package action;

import java.util.List;

import dao.StudentDao;

import model.Student;

public class StudentAction {

    /**
     * @param args
     */
    public static void main(String[] args) {
        StudentDao studentDao = new StudentDao();
        // TODO Auto-generated method stub
        System.out.println("========================查询所有学生========================");
        List<Student> students =studentDao.selectStudentList();
        for(int i=0;i<students.size();i++){
            System.out.println(students.get(i).toString());
        }
        System.out.println("========================修改学生信息========================");
        Student stu2 = new Student("Jam",20,98.4);
        stu2.setId(2);
        studentDao.updateStudent(stu2);
        System.out.println("========================通过id查询学生========================");
        Student student = studentDao.selectStudent(2);
        System.out.println(student.toString());
        System.out.println("========================增加学生========================");
        Student stu = new Student("new name",20,98.4);
        studentDao.addStudent(stu);
        System.out.println("========================删除学生信息========================");
        studentDao.deleteStudent(4);
        System.out.println("========================查询所有学生========================");
        students =studentDao.selectStudentList();
        for(int i=0;i<students.size();i++){
            System.out.println(students.get(i).toString());
        }
    }

}

The result of execution:
JDBC [1]-primary addition, deletion, modification and investigation

Points to note:

  1. After the database is created, the user needs to be given the authority to add, delete, modify, and check
  2. If you are not using maven to import the package, you need to copy the dependent package and add to path
  3. The above code uses a pre-compiled method, which can improve the readability and maintainability of the code, and it also prevents the SQL injection problem to a large extent
  4. If you are not using pre-compilation, you need to splice SQL statements, which is easy to make mistakes, and the role of pre-compilation is that after SQL is compiled, it is placed in the cache, which will be faster.
  5. Use the splicing method to refer to the following code:
    sql = "select * from table where name= '" + name + "' and password= '" + password+"'";
    Statement statement = connection.createStatement();
    ResultSet resultset = statement.executeQuery(sql);

The dependencies used by the pom file must match your own database version, or the connection fails

    <dependencies>
        <!-- mysql驱动包 -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.21</version>
        </dependency>
    </dependencies>

This article only represents my (the rookie) study accumulation record, or study notes, if there is any infringement, please contact the author to delete it. No one is perfect, so is the article, the writing is immature, not good at the next, do not spray, if there are mistakes, I hope to point out, I am grateful~

The road to technology is not at a time, the mountains are high and the rivers are long, even if it is slow, it will not stop.
Public number: Qinhuai grocery store

Guess you like

Origin blog.51cto.com/13604316/2661231