JAVA connection database JDBC programming

Provide the code to modify the database and query the database, the two are only slightly different

1. Preliminary preparation:

        Note that before connecting to the database, you must first download the JDBC driver package corresponding to the MYSQL version. For example, you must download the JDBC driver package for the MYSQL8.0 version, and you must download the MYSQL5.1 version for the MYSQL5.1 version. JDBC driver package

The version 8.0 driver package I downloaded looks like this

         After downloading the driver package, create a Directory package in your project, and paste your JDBC driver package into the package you created

        After pasting, right-click the package you created and click Add as Library (you have to tell it that you pasted it in as a library) so that the import of the JDBC driver package is completed

        2. Modify the database code:

import com.mysql.cj.jdbc.MysqlDataSource;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wuyulin
 * Date: 2023-07-19
 * Time: 14:55
 */
public class JDBCdemo1Insert {
    public static void main(String[] args) throws SQLException {
        //确定数据库中有一个student表(id,name)往里面插入一个数据

        //一,创建数据源(数据库服务器在哪里)
        DataSource dataSource = new MysqlDataSource();    //典型的向上转型
        //设置属性
        //1.填入数据库服务器所在的位置
        ((MysqlDataSource) dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/jdbcexercise?characterEncoding=utf8&useSSL=false&serverTimezone=UTC"); //向下转型

        //用下面这个方法也是一样的,但是上面的方法可以降低mysql驱动包和项目之间的偶合关系,避免后面更换数据库时有太大成本
        //MysqlDataSource mysqlDataSource=new MysqlDataSource();
        //mysqlDataSource.setUrl();
        //2.填入数据库的用户名
        ((MysqlDataSource) dataSource).setUser("root");
        //3.填入数据库的密码
        ((MysqlDataSource) dataSource).setPassword("1868397383q");
        //到这里,只是描述了一下数据库服务器所在的地址,还没有真正的连接数据库服务器

        //二.与数据库服务器建立连接
        Connection connection = dataSource.getConnection();   //建立网络连接会有很多异常,可以抛给上一级进行处理

        //三.构造sql语句
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入id");
        int id =sc.nextInt();
        System.out.println("请输入name");
        String name=sc.next();
        String sql = "insert into student values(?,?)"; //?表示占位符,表示后面再赋值
        //把String类型的sql语句转换成PreparedStatement类型的语句再传递给mysql服务器
        //Statement类型的sql语句也可以传递给mysql服务器,但是一般推荐用PreparedStatement
        //PreparedStatement会再传递给mysql服务器前在客户端这边进行初步解析,这样就能减少服务器的压力,而Statement不会进行初步解析
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setInt(1,id); //设置第一个?是整数,为id变量
        statement.setString(2,name);    //设置第二个?是字符串,为name变量

        //四.执行sql语句
        int n = statement.executeUpdate();
        //返回值n表示被影响的数据行数
        System.out.println(n + "条记录被影响");

        //五.释放必要的资源,关闭连接
        //创建的语句对象,连接对象,这些资源不用了要及时释放
        //要注意关闭的顺序,先创建的后关闭,后创建的先关闭
        statement.close();
        connection.close();
    }
}

1. Suppose there is a table in the database

        Suppose there is a student table (id, name) in the database, now we want to insert a data into it (you can create this table in the database first for inspection)

2. Create a data source (where is the database server)

        The code for creating a data source uses DataSource dataSource = new MysqlDataSource() is a parent class reference pointing to a subclass object. Upward transformation is used, and (MysqlDataSource) dataSource) is used for downcasting, because only subclass MysqlDataSource objects can call setUrl and other methods. When we create a data source, we can also directly create a MysqlDataSource reference pointing to the MysqlDataSource object, and then directly use the MysqlDataSource reference to call setUrl and other methods, so there is no need to use up and down transformation, but we use this method of transformation It can reduce the coupling relationship between the mysql driver package and the project, and avoid too much cost when replacing the database later.

        The parameter entered in setUrl() is the URL of your current computer database (the location of the database resource)

Composition of URLs

         In addition to the introduction in this photo, I also added serverTimezone=UTC. The reason for adding this is mentioned in the two errors encountered in JDBC programming to connect to the MySQL database.

        setUser() is the username of the database

        setPassword() is the password for the database

3. Establish a connection with the database

        Call the getConnection() method of the data source dataSource to establish a connection, and assign the return value to a reference of the Connection type

4. Construct sql statement

        We write the sql statement as a String type object, and then call the prepareStatement(sql) method through the connection reference to convert the String type sql statement into a PreparedStatement type sql statement,

Why use the PreparedStatement type instead of the Statement type

        SQL statements of Statement type can also be passed to the mysql server, but it is generally recommended to use PreparedStatement.
        PreparedStatement will perform preliminary analysis on the client side before passing it to the mysql server, which can reduce the pressure on the server, while Statement will not perform preliminary analysis. So we generally recommend using the PreparedStatement type

5. Execute sql statement

        The executeUpdate() method is called to execute the sql statement through the statement reference, and the database is modified. For example, the executeUpdate() method is called for adding, deleting, and modifying, and the executeQuery() method is used for querying the database.

        Calling the executeUpdate() method puts back the number of rows that affect the database, and the executeQuery() method returns the Queryed table of the ResultSet type, and then outputs the query results by traversing the ResultSet type of table

6. Release the necessary resources and close the connection

        To maintain good programming habits, create statement objects and connection objects. These resources should be released in time when they are not used. Pay attention to the
        order of release. Create first and then release, and those created later will be released first.

3. Query the code of the database

import com.mysql.cj.jdbc.MysqlDataSource;
import com.mysql.cj.protocol.Resultset;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Scanner;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: wuyulin
 * Date: 2023-07-19
 * Time: 20:06
 */
public class JDBCdemo3Select {
    public static void main(String[] args) throws SQLException {
        //1.创建数据源‘
        DataSource dataSource=new MysqlDataSource();
        ((MysqlDataSource)dataSource).setUrl("jdbc:mysql://127.0.0.1:3306/jdbcexercise?characterEncoding=utf8&useSSL=false&serverTimezone=UTC");
        ((MysqlDataSource)dataSource).setUser("root");
        ((MysqlDataSource)dataSource).setPassword("1868397383q");

        //2.连接数据库
        Connection connection=dataSource.getConnection();

        //3.构造sql语句
        Scanner sc=new Scanner(System.in);
        System.out.println("请输入要查询的id");
        int id=sc.nextInt();
        String sql="select * from student where id=?";
        PreparedStatement preparedStatement=connection.prepareStatement(sql);
        preparedStatement.setInt(1,id);

        //4.执行sql
        ResultSet resultset=preparedStatement.executeQuery();   //ResultSet是表格,查询sql语句执行返回的是表格
        //遍历表格
        while (resultset.next()){
            int student_id=resultset.getInt("id");
            String student_name=resultset.getString("name");
            System.out.println("id="+student_id+",name="+student_name);
        }

        //释放资源
        resultset.close();
        preparedStatement.close();
        connection.close();
    }
}

How to traverse a temporary table of type ResultSet

        

Guess you like

Origin blog.csdn.net/q322359/article/details/131849104