JDBC - JDBC database operation steps

1. Load a Driver

2. Create a database connection (Connection)

3. Create SQL command sender Statement

4. Create SQL

5. Send SQL commands through Statement and get the results

6. Process SQL results (select statement)

7. Close database resources

        ResultSet

        Statement

        Connection

 1. Use JDBC to complete the adding operation

package com.cspowernode.p2;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Test01Add {
    // 驱动器路径
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    //连接数据库地址
    private static final String URL = "jdbc:mysql://localhost:3306/whpowernode?useUnicode=true&useSSL=false&characterEncoding=UTF8";
    //数据库用户名
    private static final String USER_NAME = "root";
    //数据库密码
    private static final String USER_PASSWORD = "root";
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 加载驱动
        Class.forName(DRIVER);
        // 建立和数据库的连接
        Connection conn = DriverManager.getConnection(URL, USER_NAME, USER_PASSWORD);
        // 创建SQL命令发送器
        Statement stmt = conn.createStatement();
        // 使用SQL命令发送器发送SQL命令并得到结果
        String sql = "insert into student values(1,'小刚',32,'男','湖北省武汉市')";
        int n = stmt.executeUpdate(sql);
        // 处理结果
        if (n > 0) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
        // 关闭数据库资源
        stmt.close();
        conn.close();
    }
}


2. Use JDBC to complete the update operation

package com.cspowernode.p1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;


public class Test02Update {
    // 驱动器路径
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    //连接数据库地址
    private static final String URL = "jdbc:mysql://localhost:3306/whpowernode?useUnicode=true&useSSL=false&characterEncoding=UTF8";
    //数据库用户名
    private static final String USER_NAME = "root";
    //数据库密码
    private static final String USER_PASSWORD = "root";
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 加载驱动
        Class.forName(DRIVER);
        // 建立数据库的连接
        Connection conn=DriverManager.getConnection(URL, USER_NAME, USER_PASSWORD);
        // 创建SQL命令的发送器
        Statement stat=conn.createStatement();
        // 编写SQL
        String sql="update student set name='小明',age=23,sex='女',address='武汉' where id=1";
        // 使用SQL命令发送器发送SQL命令并得到结果
        int res=stat.executeUpdate(sql);
        // 处理结果
        if(res>0){
            System.out.println("修改成功");
        }
        else{
            System.out.println("处理失败");
        }
        // 关闭数据库资源
        stat.close();
        conn.close();
    }
}

3. Use JDBC to complete the deletion operation

package com.cspowernode.p1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Test03Delete {
    // 驱动器路径
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    //连接数据库地址
    private static final String URL = "jdbc:mysql://localhost:3306/whpowernode?useUnicode=true&useSSL=false&characterEncoding=UTF8";
    //数据库用户名
    private static final String USER_NAME = "root";
    //数据库密码
    private static final String USER_PASSWORD = "123456";
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        // 加载驱动
        Class.forName(DRIVER);
        // 建立数据库的连接
        Connection conn=DriverManager.getConnection(URL, USER_NAME, USER_PASSWORD);
        // 创建SQL命令的发送器
        Statement stat=conn.createStatement();
        // 编写SQL
        String sql="delete from student where id=1";
        // 使用SQL命令发送器发送SQL命令并得到结果
        int res=stat.executeUpdate(sql);
        // 处理结果
        if(res>0){
            System.out.println("删除成功");
        }
        else{
            System.out.println("删除失败");
        }
        // 关闭数据库资源
        stat.close();
        conn.close();
    }
}

 4. Create DBUtils packaging code

package com.bjpowernode.utils;

import java.io.Closeable;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class DBUtils {
    // 驱动器路径
    private static final String DRIVER = "com.mysql.jdbc.Driver";
    // 连接数据库地址
    private static final String URL = "jdbc:mysql://localhost:3306/whpowernode?useUnicode=true&useSSL=false&characterEncoding=UTF8";
    // 数据库用户名
    private static final String USER_NAME = "root";
    // 数据库密码
    private static final String USER_PASSWORD = "123456";

    /**
     * 静态加载驱动程序
     */
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * @return 连接对象
     */
    public static Connection getConn() {
        try {
            return  DriverManager.getConnection(URL, USER_NAME, USER_PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("创建连接对象异常");
        }
        return null;
    }

    /**
     * 关闭资源
     */
    public static void close(AutoCloseable closeable) {
        try {
            if (closeable != null) {
                closeable.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

5. Add operations after using DBUtils to encapsulate the code

package com.bjpowernode.jdbc;

import com.bjpowernode.utils.DBUtils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;

public class Test01Add {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Connection conn = DBUtils.getConn();
        // 创建SQL命令发送器
        Statement stmt = conn.createStatement();
        // 使用SQL命令发送器发送SQL命令并得到结果
        String sql = "insert into student values(1,'小刚',32,'男','湖北省武汉市')";
        int n = stmt.executeUpdate(sql);
        // 处理结果
        if (n > 0) {
            System.out.println("添加成功");
        } else {
            System.out.println("添加失败");
        }
        // 关闭数据库资源
        DBUtils.close(stmt);
        DBUtils.close(conn);
    }
}

6. Use DBUtils to add 20 pieces of data to the table

package com.bjpowernode.jdbc;

import com.bjpowernode.utils.DBUtils;

import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Random;

public class Test01Add20 {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Connection conn = DBUtils.getConn();
        // 创建SQL命令发送器
        Statement stmt = conn.createStatement();
        // 使用SQL命令发送器发送SQL命令并得到结果
        Random random=new Random();
        for (int i = 1; i <=20 ; i++) {
            Integer id=i;
            String name="小明"+i;
            int age=random.nextInt(100);
            String sex=random.nextBoolean()?"男":"女";
            String address="武汉"+i;

            String sql = "insert into student values("+i+",'"+name+"',"+age+",'"+sex+"','"+address+"')";
            int n = stmt.executeUpdate(sql);
            // 处理结果
            if (n > 0) {
                System.out.println("添加成功");
            } else {
                System.out.println("添加失败");
            }
        }
        // 关闭数据库资源
        DBUtils.close(stmt);
        DBUtils.close(conn);
    }
}

7. Use JDBC to complete paging queries

package com.bjpowernode.jdbc;

import com.bjpowernode.utils.DBUtils;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Test05QueryForPage {
    public static void main(String[] args) throws ClassNotFoundException, SQLException {
        Connection conn = DBUtils.getConn();
        // 创建SQL命令发送器
        Statement stmt = conn.createStatement();
        int pageNum=2; //页码
        int pageSize=5;//每页显示的条数
        // 编写SQL
        String sql="select * from student limit "+(pageNum-1)*pageSize+","+pageSize;
        // 使用SQL命令发送器发送SQL命令并得到结果
        ResultSet rs=stmt.executeQuery(sql);
        // 处理结果
        while(rs.next()){
            int id=rs.getInt(1);
            String name=rs.getString(2);
            int age=rs.getInt(3);
            String sex=rs.getString(4);
            String address=rs.getString(5);
            System.out.println(id+"  "+name+"  "+age+"   "+sex+"   "+address);
        }
        // 关闭数据库资源
        DBUtils.close(rs);
        DBUtils.close(stmt);
        DBUtils.close(conn);
    }
}

 

Connection conn = DBUtils.getConn();

Statement stmt = conn.creatStatement();

ResultSet rs = stmt.executeQuery(sql);//Execute query

int n = stmt.executeUpdate(sql);//Execute additions, deletions and modifications

 

 

 

 

Guess you like

Origin blog.csdn.net/shengshanlaolin_/article/details/128462105