• 大小: 6KB
    文件类型: .java
    金币: 1
    下载: 0 次
    发布日期: 2021-05-28
  • 语言: Java
  • 标签: java  mysql  

资源简介

写好sql语句,调用该工具类内的方法,即可实现增删改查mysql数据库的操作。带有详细解释

资源截图

代码片段和文件信息

package db;

/*
 * To change this license header choose License Headers in Project Properties.
 * To change this template file choose Tools | Templates
 * and open the template in the editor.
 */

import com.sun.rowset.CachedRowSetImpl;
import java.sql.*;
import javax.sql.rowset.CachedRowSet;

/**
 *
 * @author Administrator
 */
public class DBUtil {
static String _url = “jdbc:mysql://localhost:3306/test“;
static String _username = “root“;
static String _password = “root“;
    //按传入的SQL进行数据库查询操作
    @SuppressWarnings(“finally“)
public static CachedRowSet querySQL(String sql) throws SQLException {
        //离线集合
        CachedRowSet crs = new CachedRowSetImpl();
        //定义数据库连接对象·Connection.   定义传输对象.   定义结果集对象
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            //加载Driver驱动
            Class.forName(“com.mysql.jdbc.Driver“);
            //创建数据库连接对象connection  localhost:3306分别为本机ip和数据库接入端口号
            conn = DriverManager.getConnection(_url _username _password);
            //创建一个可向数据库发送SQL命令并返回结果的传送对象
            stmt = conn.createStatement();
            //将sql命令通过sql传送对象传送到数据库执行
            rs = stmt.executeQuery(sql);
            //处理结果集
            crs.populate(rs);
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            //手动关闭资源
            if (rs != null) {
                try {
                    rs.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (stmt != null) {
                try {
                    stmt.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            if (conn != null) {
                try {
                    conn.close();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
            return crs;
        }
    }

    //按传入的SQL进行数据库更新操作(单条、无事务)
    @SuppressWarnings(“finally“)
public static boolean  updateSQL(String sql) {
        boolean rtn = false;
        //定义数据库连接对象·Connection定义传输对象
        Connection conn = null;
        Statement stmt = null;
        try {
            //加载Driver驱动
            Class.forName(“com.mysql.jdbc.Driver“);
            //创建数据库连接对象connection
            conn = Driver

评论

共有 条评论