JDBC database programming

Create a new table in the database, insert data : create a
new database: the name is school
write picture description here
column (header)
write picture description here
write picture description here

Note: auto_increment stands for auto-increment. only for int

Insert data:
write picture description here
View table:
write picture description here


Store the sql statement in the project:
build Folder, name sql
build File, name database ming.sql. For example: school.sql

write picture description here

Open the copy into the sql statement:
write picture description here

E.g:

INSERT into student VALUES (1, ‘abc’, 20);
INSERT INTO student(name, age) VALUES (‘zs’, 20);
INSERT INTO student VALUES (null, ‘abb’, 20);


Program:
Query: By Column Name

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", "root", "");//协议+数据库+端口号+数据库名---------用户名--------密码为空
//        System.out.println(con);



        //3准备执行语句
        String sql = "select * from student";
        PreparedStatement pst = con.prepareStatement(sql);


        //4执行
        ResultSet rs = pst.executeQuery();//结果集为一个二维表
        while(rs.next()){//返回true,代表有数据可以读取
            int id = rs.getInt("id");//参数字段名称为数据库的表头(列的名称)
            String name = rs.getString("name");
            int age = rs.getInt("age");
            System.out.println(id + "--" + name + "--" + age);
        }

        //5关闭资源,关闭连接
        rs.close();
        pst.close();
        con.close();
    }
}

Output:
1–abc–20
2–Zhangsan–20
3–abc–20

Improvements to Query: By Column's Ordinal

 //4执行
        ResultSet rs = pst.executeQuery();//结果集为一个二维表
        while(rs.next()){//返回true,代表有数据可以读取
            int id = rs.getInt(1);//列是从1开始的
            String name = rs.getString(2);
            int age = rs.getInt(3);
            System.out.println(id + "--" + name + "--" + age);
        }

The output is the same as above

Additions, deletions and modifications:

increase:

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", "");//协议+数据库+端口号+数据库名---------用户名--------密码为空
        //为了插入汉字,所以需要?useUnicode=true&characterEncoding=utf-8


        //3insert
        //有未知数,用?占位
        String insertSQL = "insert into student values(null, ?, ?)";//准备sql语句
        PreparedStatement pst1 = con.prepareStatement(insertSQL);//准备sql语句的对象

        //给?赋值
        pst1.setString(1, "李四");
        pst1.setInt(2, 25);

        int result = pst1.executeUpdate();//对于增删改用update,返回类型为int型
        if(result == 1){
            System.out.println("插入记录成功!");
        }
        //4delete


        //5update


        String sql = "select * from student";
        PreparedStatement pst = con.prepareStatement(sql);
        //6查询
        ResultSet rs = pst.executeQuery();//对于查询用Query,返回类型为二维表
        while(rs.next()){//返回true,代表有数据可以读取
            int id = rs.getInt(1);//列是从1开始的
            String name = rs.getString(2);
            int age = rs.getInt(3);
            System.out.println(id + "--" + name + "--" + age);
        }

        //7关闭资源,关闭连接
        rs.close();
        pst.close();
        con.close();
    }
}

Output:
Inserting records succeeded!
1–abc–20
2–Zhang San–20
3–abc–20
4–Li Si–25

delete:

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", "");//协议+数据库+端口号+数据库名---------用户名--------密码为空


       /* //3insert
        String insertSQL = "insert into student values(null, ?, ?)";//准备sql语句
        PreparedStatement pst1 = con.prepareStatement(insertSQL);//准备sql语句的对象
        //给?赋值
        pst1.setString(1, "李四");
        pst1.setInt(2, 25);

        int result = pst1.executeUpdate();
        if(result == 1){
            System.out.println("插入记录成功!");
        }*/

        //4delete
        String deleteSQL = "delete from student where id=?";//准备要执行sql语句
        PreparedStatement pst2 = con.prepareStatement(deleteSQL);//准备sql语句的对象
        pst2.setInt(1, 1);

        int result1 = pst2.executeUpdate();
        if(result1 == 1){
            System.out.println("删除记录成功!");
        }

        //5update



        //6查询所有记录
        String sql = "select * from student";
        PreparedStatement pst = con.prepareStatement(sql);

        ResultSet rs = pst.executeQuery();//结果集为一个二维表
        while(rs.next()){//返回true,代表有数据可以读取
            int id = rs.getInt(1);//列是从1开始的
            String name = rs.getString(2);
            int age = rs.getInt(3);
            System.out.println(id + "--" + name + "--" + age);
        }

        //7关闭资源,关闭连接
        rs.close();
        pst.close();
        con.close();
    }
}

Output:
delete record successful!
2 – Zhang San – 20
3 – abc – 20
11 – Li Si – 25

Change (update):

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", "");//协议+数据库+端口号+数据库名---------用户名--------密码为空


       /* //3insert
        String insertSQL = "insert into student values(null, ?, ?)";//准备sql语句
        PreparedStatement pst1 = con.prepareStatement(insertSQL);//准备sql语句的对象
        //给?赋值
        pst1.setString(1, "李四");
        pst1.setInt(2, 25);

        int result = pst1.executeUpdate();
        if(result == 1){
            System.out.println("插入记录成功!");
        }*/

        /*//4delete
        String deleteSQL = "delete from student where id=?";//准备要执行sql语句
        PreparedStatement pst2 = con.prepareStatement(deleteSQL);//准备sql语句的对象
        pst2.setInt(1, 1);

        int result1 = pst2.executeUpdate();
        if(result1 == 1){
            System.out.println("删除记录成功!");
        }
        */

        //5update
        String updateSQL = "update student set name = ?,age = ? where id = ?";
        //?的意思是:待输入的值
        PreparedStatement pst3 = con.prepareStatement(updateSQL);
        pst3.setString(1, "吴振浩");
        pst3.setInt(2, 55);
        pst3.setInt(3, 2);

        int result2 = pst3.executeUpdate();
        if(result2 == 1){
            System.out.println("修改记录成功!");
        }



        //6查询所有记录
        String sql = "select * from student";
        PreparedStatement pst = con.prepareStatement(sql);

        ResultSet rs = pst.executeQuery();//结果集为一个二维表
        while(rs.next()){//返回true,代表有数据可以读取
            int id = rs.getInt(1);//列是从1开始的
            String name = rs.getString(2);
            int age = rs.getInt(3);
            System.out.println(id + "--" + name + "--" + age);
        }

        //7关闭资源,关闭连接
        rs.close();
        pst.close();
        con.close();
    }
}

Output:
Modify the record successfully!
2 – Wu Zhenhao – 55
3 – abc – 20
11 – Li Si – 25

In the navicat visualization, the new database is:
write picture description here


Package:

Sdutent.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;
    }

    //因为三个属性是私有的,所有可以通过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;
    }


}

StudentDao.java

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
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 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, id);

        int result = pst.executeUpdate();

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

    }

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

        int result = pst.executeUpdate();

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

    }


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

        return null;
    }


    //根据主键查询记录
    public Student queryById(int id){
        return null;
    }
}

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326992796&siteId=291194637