Connect Java to the database (configure idea) to implement a simple library management system

Table of contents

1. Connect Java and Mysql database through connector

(1) First configure the idea

(2) How to connect java and mysql

1. Simple connection

2. Get to know PrepareStatement

2. Implement a simple library management system

(1) Create database jdbc and create book table

 (2) Write code in idea to connect mysql with java to implement basic addition, deletion, modification and query

1.JdbcUtiles class, a tool class that uses jdbc

 2.BookDb class, realizing addition, deletion, modification and query

3.testMain class, running location


1. Connect Java and Mysql database through connector

(1) First configure the idea

The database we use here is version Mysql8.0. Note that the connector of version 8.0 needs to use 8.0. If you use 5.0, an error will be reported. Download URL: MySQL:: Download Connector/J  After the download is completed, click the plus sign and configure it in the idea. After the configuration is completed, there will be newly added class packages in the externLibrary of idea.

 Our preliminary task is completed!

(2) How to connect java and mysql

1. Simple connection

String url = "jdbc:mysql://localhost:3306/jdbc?useSSL=false";
String user = "root";
String password = "18342003" ; 
try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection(url,user, password);
}catch(SQLEXCEPTION ex){
    ex.printStackTrace();
}finally{
            try {
                con.close();
                st.close();
                rs.close();
            }catch(Exception ex){
                ex.printStackTrace();
            }

        }

Through this code we can achieve a simple connection between java and mysql. It should be noted that url = jdbc:mysql://hostname:domain name/database name user = username password = password Students with mysql basics should easily understand, finally We close the connection. This enables a simple connection

After connecting, we can write several sql statements to check whether

try {
            Class.forName("com.mysql.cj.jdbc.Driver");
            con = DriverManager.getConnection(url,user, password);

            String sql_insert = "insert into student values(10,'aa',30)";
            String sql_insert1 = "insert into student values(11,'aa',30)";
            String sql_insert2 = "insert into student values(12,'aa',30)";
            String sql_select = "select  * from student";
            //执行sql语句
           st.executeUpdate(sql_insert);
            st.executeUpdate(sql_insert1);
            st.executeUpdate(sql_insert2);

   
            while(rs.next()){
                System.out.println(rs.getInt(1)+","+
                        rs.getString(2)+","+
                        rs.getInt(3)
                        );
            }

        }catch(Exception ex){
            ex.printStackTrace();
        }finally{
            try {
                con.close();
                st.close();
                rs.close();
            }catch(Exception ex){
                ex.printStackTrace();
            }

2. Get to know PrepareStatement

But specifically when adding a database, the sql statement we write cannot be dead, it must change, so we have PrepareStatement to write the changed sql statement. The specific content is as follows

PreparedStatement preparedStatement = con.prepareStatement("insert into student values(?,?,?)");
         preparedStatement.setInt(1,3);
         preparedStatement.setString(2,"abc");
         preparedStatement.setInt(3,20);
         preparedStatement.executeUpdate();

2. Implement a simple library management system

(1) Create database jdbc and create book table

You can enter create database jdbc; in the cmd command line, or you can create it directly in navicat

 (2) Write code in idea to connect mysql with java to implement basic addition, deletion, modification and query

1.JdbcUtiles class, a tool class that uses jdbc

package myDatebases_Demo;
import java.util.*;
import java.sql.*;

public class JdbcUtil {
    private static final String DRIVER = "com.mysql.cj.jdbc.Driver";
    private static final String URL = "jdbc:mysql://localhost:3306/jdbc?useSSL=false";
    private static final String USER = "root";
    private static final String PASSWORD = "18342003";

    //注册驱动程序放在代码块中,每次只能注册一次
        static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }

    //创建getConnection对象,用来获得connection对象
    public static Connection getConnection(){
            Connection conn = null;
            try {
                conn = DriverManager.getConnection(URL,USER,PASSWORD);
            }catch (SQLException e){
                e.printStackTrace();
            }
        return conn;
    }

    //创建free方法实现关闭连接功能
    public static void close(Statement st, Connection conn) {
        if (st != null) {
            try {
                st.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (conn != null) {
                    try {
                        conn.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    public static void close(ResultSet rs, Statement st, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            } finally {
                if (st != null) {
                    try {
                        st.close();
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } finally {
                        if (conn != null) {
                            try {
                                conn.close();
                            } catch (SQLException e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
        }
    }
}

This class can be used in any system. It is universal and can be copied and pasted directly. After all, Java is a copy-oriented

programming language

                              

 2.BookDb class, realizing addition, deletion, modification and query

        1.increase

public static void addBook(Book s) {
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("insert into book values (?,?,?)");
            pst.setInt(1, s.getId());
            pst.setString(2, s.getName());
            pst.setString(3, s.getPress());
            pst.executeUpdate();
            JdbcUtil.close(pst, conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

        2.Delete


    //根据书本id删除书本信息
    public static void delectBook(int id){
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("delete from book where id = ?");
            pst.setString(1, String.valueOf(id));
            pst.executeUpdate();
            JdbcUtil.close(pst, conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

        3.Change

//根据书本id更新书本信息
    public static void updateBook(Book b, int id) {
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("update book set id = ?,name = ?,press = ? where id = ? ");
            pst.setInt(1, b.getId());
            pst.setString(2, b.getName());
            pst.setString(3, b.getPress());
            pst.executeUpdate();
            JdbcUtil.close(pst, conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

        4.Check

//根据书本id查询书本的信息
    //保存在一个对象中,用于集中输出,或者放在集合中,用于管理输出等
    public static Book findBookById(int id) {
        Book b = new Book();
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("select * from  book where id = ?");
            pst.setInt(1, id);
            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                b.setId(rs.getInt(1));
                b.setName(rs.getString(2));
                b.setPress(rs.getString(3));
            }
            JdbcUtil.close(rs, pst, conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return b;
    }

Put all the information in an object container, and use the object container for output, because when we specifically query the information of a table in mysql, each category of the table is a field, and each row can correspond to a field in java. Object, so we can put all the found information in an object, representing each row of our table

        5. Show all information

 //查询书本的所有信息,保存在一个集合中,后来再通过集合再把所有结果输出出来,避免此中语句过于冗杂,利于以后的更改
    public static ArrayList<Book> queryBook() {
        ArrayList<Book> list = new ArrayList<>();
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("select * from book");
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                Book b = new Book();
                b.setId(rs.getInt(1));
                b.setName(rs.getString(2));
                b.setPress(rs.getString(3));
                list.add(b);
            }
            JdbcUtil.close(rs,pst,conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return list;
    }

It will be easier to understand here. Put each row obtained in the list container and then output it.

All codes:

package myDatebases_Demo;

import java.sql.*;
import java.util.ArrayList;

public class BookDb {
    public static void addBook(Book s) {
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("insert into book values (?,?,?)");
            pst.setInt(1, s.getId());
            pst.setString(2, s.getName());
            pst.setString(3, s.getPress());
            pst.executeUpdate();
            JdbcUtil.close(pst, conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    //根据书本id删除书本信息
    public static void delectBook(int id){
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("delete from book where id = ?");
            pst.setString(1, String.valueOf(id));
            pst.executeUpdate();
            JdbcUtil.close(pst, conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    //根据书本id更新书本信息
    public static void updateBook(Book b, int id) {
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("update book set id = ?,name = ?,press = ? where id = ? ");
            pst.setInt(1, b.getId());
            pst.setString(2, b.getName());
            pst.setString(3, b.getPress());
            pst.executeUpdate();
            JdbcUtil.close(pst, conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }
    }

    //根据书本id查询书本的信息
    //保存在一个对象中,用于集中输出,或者放在集合中,用于管理输出等
    public static Book findBookById(int id) {
        Book b = new Book();
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("select * from  book where id = ?");
            pst.setInt(1, id);
            ResultSet rs = pst.executeQuery();
            if (rs.next()) {
                b.setId(rs.getInt(1));
                b.setName(rs.getString(2));
                b.setPress(rs.getString(3));
            }
            JdbcUtil.close(rs, pst, conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return b;
    }

    //查询书本的所有信息,保存在一个集合中,后来再通过集合再把所有结果输出出来,避免此中语句过于冗杂,利于以后的更改
    public static ArrayList<Book> queryBook() {
        ArrayList<Book> list = new ArrayList<>();
        try {
            Connection conn = JdbcUtil.getConnection();
            PreparedStatement pst = conn.prepareStatement("select * from book");
            ResultSet rs = pst.executeQuery();
            while (rs.next()) {
                Book b = new Book();
                b.setId(rs.getInt(1));
                b.setName(rs.getString(2));
                b.setPress(rs.getString(3));
                list.add(b);
            }
            JdbcUtil.close(rs,pst,conn);
        } catch (SQLException ex) {
            ex.printStackTrace();
        }

        return list;
    }
}

3.testMain class, running location


import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.Scanner;

public class testMain {
    public static void main(String[] args) throws IOException {
        Scanner sc = new Scanner(System.in);


        while (true) {
            Meau();
            int choose = sc.nextInt();
            switch (choose) {
                case 1:
                    Book b = getBook();
                    BookDb.addBook(b);
                    //看了好多文章,好像都无法实现清空控制台的功能,这个是最实用的
                    break;
                case 2:
                    System.out.println("请输入想要删除的书本的id");
                    int id = sc.nextInt();
                    BookDb.delectBook(id);

                    break;
                case 3:
                    System.out.println("请输入想要更新的书本的id");
                    Book b1 = getBook();
                    int id1 = sc.nextInt();
                    BookDb.updateBook(b1,id1);

                    break;
                case 4:
                    System.out.println("请输入想要查询的书本的id");
                    int id2 = sc.nextInt();
                    Book b2 = BookDb.findBookById(id2);
                    System.out.println("id\t\t name\t\t press\t");
                    System.out.println(b2.getId()+"\t\t"+b2.getName()+"\t\t"+b2.getPress());

                    break;
                case 5:
                    System.out.println(BookDb.queryBook().size());
                    queryBook(BookDb.queryBook());
                    break;
            }
        }
    }

    public static void queryBook(ArrayList<Book> list){
        System.out.println("id\t\t name\t\t press\t");
        for (int i = 0; i < list.size(); i++) {
            System.out.println(list.get(i).getId()+"\t\t"+list.get(i).getName()+"\t\t"+list.get(i).getPress()+"\t");
        }

    }

    public static Book getBook(){
        Book b = new Book();
        Scanner sc = new Scanner(System.in);
        System.out.println("请输入书本id:");
        b.setId(sc.nextInt());
        System.out.println("请输入书本名称:");
        b.setName(sc.next());
        System.out.println("请输入书本出版社名称: ");
        b.setPress(sc.next());

        return b;
    }

    public static void Meau(){
        System.out.println("欢迎进入图书馆管理系统");
        System.out.println("1 增加");
        System.out.println("2 删除");
        System.out.println("3 修改");
        System.out.println("4 查询");
        System.out.println("5 显示全部信息");
        System.out.println("6 退出");
    }
}

Take a look at the effect

 

Hehe, we're done! !

 

 

Guess you like

Origin blog.csdn.net/weixin_73733267/article/details/131115965