1.jdbc是什么

  • JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序。(百度百科)

  • jdbc经常用来连接数据库,创建sql或者mysql语句,使用相关的api去执行sql语句,从而操作数据库,达到查看或者修改数据库的目的。

  • 学习jbbc要求对java编程有一定了解,并了解一种数据库系统以及sql语句。

  • 环境要求:

1.本地装好jdk,并且装好mysql数据库,我是直接装过wamp带有mysql数据库/docker中安装的mysql。
2.使用IDEA开发

2.使用IDEA开发

2.1 创建数据库,数据表

我的mysql是使用docker创建的,如果是windows环境可以使用wamp较为方便。

数据库名字是test,数据表的名字是student,里面有四个字段,一个是id,也就是主键(自动递增),还有名字,年龄,成绩。最后先使用sql语句插入六个测试记录。

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 使用IDEA创建项目

我使用maven工程方式,项目目录:

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());
        }
    }

}

执行的结果:

需要注意的点:

  1. 创建数据库之后需要赋予用户增删改查的权限
  2. 如果不是使用maven方式导入包,需要将依赖的包复制进来,并且add to path
  3. 以上代码使用的是预编译的方式,这样可以提高代码的可读性与维护性,还有就是很大程度上防止了sql注入的问题
  4. 如果不是用预编译,那么就需要拼接sql语句,很容易出错,而且预编译的作用是sql编译过后,放在缓存中,这样速度会更快。
  5. 使用拼接方式参考下面这段代码:
    sql = "select * from table where name= '" + name + "' and password= '" + password+"'";
    Statement statement = connection.createStatement();
    ResultSet resultset = statement.executeQuery(sql);

pom文件使用到的依赖,必须和自己的数据库版本匹配,要不会连接失败

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

【作者简介】
秦怀,公众号【秦怀杂货店】作者,技术之路不在一时,山高水长,纵使缓慢,驰而不息。这个世界希望一切都很快,更快,但是我希望自己能走好每一步,写好每一篇文章,期待和你们一起交流。

此文章仅代表自己(本菜鸟)学习积累记录,或者学习笔记,如有侵权,请联系作者核实删除。人无完人,文章也一样,文笔稚嫩,在下不才,勿喷,如果有错误之处,还望指出,感激不尽~