springboot集成dbutils、jdbc查询数据源下的数据库表格及表格字段

此功能用于系统集成多数据源的管理和查询。可管理多个数据源,根据对应的配置进行储存数据库对应的数据、便于管理和查询。
应用场景、表单的配置选取数据源,选择表格后查询出表格对应的字段名称,长度,字段的属性。
1、先配置pom.xml

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-jdbc</artifactId>
</dependency>
<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
    <groupId>commons-dbutils</groupId>
    <artifactId>commons-dbutils</artifactId>
    <version>1.7</version>
</dependency>
<dependency>
    <groupId>com.mchange</groupId>
    <artifactId>c3p0</artifactId>
    <version>0.9.5.2</version>
</dependency>

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <optional>true</optional>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
</dependency>

2、新建数据库来管理需要储存的数据库信息。新建实体类实现类进行增删改查,这里就不详细进行叙述了。
在这里插入图片描述

3、新建jdbcDome来储存驱动,连接的URL,账号,密码。

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
public class jdbcDome {

    private String driverClassName;//驱动

    private String jdbcUrl;//数据库URL

    private String userName;//数据库账号

    private String passWord;//数据库密码



}

4、新建JDBCUtils来管理连接

import com.hsdev.biz.qu.entity.jdbcDome;

import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Map;

public class JDBCUtils {
    public static Connection getConnection(jdbcDome jdbc) throws Exception{

        Connection connection = null;
        //Class.forName("com.mysql.cj.jdbc.Driver");
        //此处是写死的MySql的驱动。也可根据配置进行配置。
        DriverManager.registerDriver(new com.mysql.cj.jdbc.Driver());
        connection = DriverManager.getConnection(jdbc.getJdbcUrl(), jdbc.getUserName(), jdbc.getPassWord());
        return connection;
    }
}

5、新建DBUtilsController方法进行查询返回值的设置

import com.hsdev.biz.qu.entity.SysDataSource;
import com.hsdev.biz.qu.entity.jdbcDome;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class DBUtilsController {

    /**
     *
     * @return
     * @throws Exception
     */
    //查询
    public static List<Map<String,Object>> queryAllStudent(String sql,
                                                           SysDataSource sysDataSource) throws Exception{
        //1.  获取连接对象
        jdbcDome jdbc = new jdbcDome();
        jdbc.setDriverClassName(sysDataSource.getDbDriver());
        jdbc.setJdbcUrl(sysDataSource.getDbUrl());
        jdbc.setUserName(sysDataSource.getDbUserName());
        jdbc.setPassWord(sysDataSource.getDbPassword());
        Connection connection = JDBCUtils.getConnection(jdbc);
        //2.创建执行对象
        PreparedStatement pstmt = connection.prepareStatement(sql);

        //3.执行SQL查询,返回结果集对象
        ResultSet rs = pstmt.executeQuery();

        //4.循环处理结果集中的每一条数据
        List<Map<String,Object>> list = new ArrayList<>();

        ResultSetMetaData md = rs.getMetaData();//获取键名
        int columnCount = md.getColumnCount();//获取行的数量
        while(rs.next()){ //rs.next()的作用,1. 返回是否有下一条数据, 2.将游标指向下一行
            Map<String,Object> map = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                map.put(md.getColumnName(i), rs.getObject(i));//获取键名及值
            }
            list.add(map);

            /*Map<String,Object> map = new HashMap<>();
            String name = rs.getString("name");
            String comment = rs.getString("comment");
            int rows = Integer.parseInt(rs.getString("rows"));
            map.put("name",name);
            map.put("comment",comment);
            map.put("rows",rows);
            list.add(map);*/

        }

        while(rs.next()){ //rs.next()的作用,1. 返回是否有下一条数据, 2.将游标指向下一行
            Map<String,Object> map = new HashMap<>();
            String name = rs.getString("name");
            String comment = rs.getString("comment");
            int rows = Integer.parseInt(rs.getString("rows"));
            map.put("name",name);
            map.put("comment",comment);
            map.put("rows",rows);
            list.add(map);

        }

        //5.关闭连接对象
        rs.close();
        pstmt.close();
        connection.close();

        //6.返回结果集
        return list;
    }

    public static List<Map<String, Object>> queryAllStudentTable(String sql,SysDataSource sysDataSource) throws Exception{
        //1.  获取连接对象
        jdbcDome jdbc = new jdbcDome();
        jdbc.setDriverClassName(sysDataSource.getDbDriver());
        jdbc.setJdbcUrl(sysDataSource.getDbUrl());
        jdbc.setUserName(sysDataSource.getDbUserName());
        jdbc.setPassWord(sysDataSource.getDbPassword());
        Connection connection = JDBCUtils.getConnection(jdbc);
        //2.创建执行对象
        PreparedStatement pstmt = connection.prepareStatement(sql);

        //3.执行SQL查询,返回结果集对象
        ResultSet rs = pstmt.executeQuery();

        //4.循环处理结果集中的每一条数据
        List<Map<String,Object>> list = new ArrayList<>();

        ResultSetMetaData md = rs.getMetaData();//获取键名
        int columnCount = md.getColumnCount();//获取行的数量
        while(rs.next()) { //rs.next()的作用,1. 返回是否有下一条数据, 2.将游标指向下一行
            Map<String, Object> map = new HashMap<>();
            for (int i = 1; i <= columnCount; i++) {
                map.put(md.getColumnName(i), rs.getObject(i));//获取键名及值
            }
            list.add(map);
        }

        /*while(rs.next()){ //rs.next()的作用,1. 返回是否有下一条数据, 2.将游标指向下一行
            Map<String,Object> map = new HashMap<>();
            String name = rs.getString("name");
            String comment = "";
            String type = rs.getString("type");
            int rows = 0;
            if (rs.getString("comment")!=null && !"".equals(rs.getString("comment"))){
                comment = rs.getString("comment");
            }
            if (rs.getString("rows")!=null && !"".equals(rs.getString("rows"))){
                Integer.parseInt(rs.getString("rows"));
            }
            map.put("name",name);
            map.put("comment",comment);
            map.put("type",type);
            map.put("rows",rows);
            list.add(map);

        }*/

        //5.关闭连接对象
        rs.close();
        pstmt.close();
        connection.close();

        //6.返回结果集
        return list;
    }

/**********************************修改、删除************************/
/**
     *
     * @param
     * @return
     * @throws Exception
     */
    //添加单个
    /*public int addStudent(User user) throws Exception{
        //1. 获取连接对象
        Connection connection = JDBCUtils.getConnection();

        //2.创建预编译对象
        String sql = "insert into user (name, age, sex, height, weight) values (?,?,?,?,?)";
        PreparedStatement pstmt = connection.prepareStatement(sql);

        //3.设置占位符参数
        pstmt.setString(1, user.getName());
        pstmt.setInt(2, user.getAge());
        pstmt.setString(3, user.getSex());
        pstmt.setInt(4, user.getHeight());
        pstmt.setInt(5, user.getWeight());

        //4.执行更新
        int effectRows = pstmt.executeUpdate();

        //5.关闭连接对象
        pstmt.close();
        connection.close();

        return effectRows;


    }


    //添加多个
    public int insertStudentByBatch(List<User> user) throws Exception{
        //1.创建连接对象
        Connection connection = JDBCUtils.getConnection();

        //2.创建预编译对象
        String sql = "insert into student (name, age, sex, height, weight) values (?, ?, ?, ?, ?)";
        PreparedStatement pstmt = connection.prepareStatement(sql);

        //3.设置占位符参数
        for(User stu : user){
            pstmt.setString(1, stu.getName());
            pstmt.setInt(2, stu.getAge());
            pstmt.setString(3, stu.getSex());
            pstmt.setInt(4, stu.getHeight());
            pstmt.setInt(5, stu.getWeight());
            pstmt.addBatch();
        }

        //4.执行更新对象
        int[] ints = pstmt.executeBatch();
        int effectRows = 0;
        for(int rows : ints){
            effectRows += rows;
        }

        //5.关闭连接
        pstmt.close();
        connection.close();

        return effectRows;
    }


    
    //删除
    public int deleteStudentByid(Integer id) throws Exception{

        //1.获取连接对象
        Connection connection = JDBCUtils.getConnection();

        //2.创建执行对象
        String sql = "delete from user where id = ?";
        PreparedStatement pstmt = connection.prepareStatement(sql);

        //3.设置占位符参数
        pstmt.setInt(1, id);

        //4.执行更新
        int effectRows = pstmt.executeUpdate();

        //5.关闭连接
        pstmt.close();
        connection.close();

        return effectRows;

    }

    //按照学号更新学生信息
    public int updateStudent(User user) throws Exception{

        //1.创建连接对象
        Connection connection = JDBCUtils.getConnection();

        //2.创建执行对象
        String sql = "update user set name = ?, age = ?, sex = ? where id = ?";
        PreparedStatement pstmt = connection.prepareStatement(sql);

        //3.设置占位符参数
        pstmt.setString(1, user.getName());
        pstmt.setInt(2, user.getAge());
        pstmt.setString(3, user.getSex());
        pstmt.setInt(4, user.getId());

        //4.执行更新
        int effectRows = pstmt.executeUpdate();

        //5.关闭连接
        pstmt.close();
        connection.close();

        return effectRows;


    }*/
/***************************************************************************************/
}

6、5里面的SysDataSource方法为存储数据库的实体类。

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("sys_datasource")
public class SysDataSource extends BaseEntity {

	private static final long serialVersionUID = 1L;

	private String name;		// 连接中文名称

	private String enname;  //数据库用户名

	private String dbPassword;		// 数据库密码

	private String dbUrl;		// 数据库链接

	private String dbDriver;		// 数据库驱动类


}

7、设置查询条件。查询某一个数据源下面的所有表格。查询某个数据源下某个表格的字段名称等数据。

/**
     * 查询表列表
     * @return
     */
    static List<Map<String,Object>> TableList(SysDataSource sysDataSource) throws Exception {
        String sql = "SELECT TABLE_NAME name,TABLE_COMMENT comment,TABLE_ROWS rows FROM information_schema.tables WHERE TABLE_SCHEMA = '"+sysDataSource.getEnname()+"' ORDER BY TABLE_NAME";
        return DBUtilsController.queryAllStudent(sql,sysDataSource);
    }

    /**
     * 查询表列表下字段
     * @return
     */
    static List<Map<String,Object>> TableListEntity(SysDataSource sysDataSource,String table) throws Exception {
        String sql = "SELECT column_NAME name,column_comment comment,column_type type ,(\n" +
                "           CASE\n" +
                "               WHEN data_type = 'float'\n" +
                "                   OR data_type = 'double'\n" +
                "                   OR data_type = 'TINYINT'\n" +
                "                   OR data_type = 'SMALLINT'\n" +
                "                   OR data_type = 'MEDIUMINT'\n" +
                "                   OR data_type = 'INT'\n" +
                "                   OR data_type = 'INTEGER'\n" +
                "                   OR data_type = 'decimal'\n" +
                "                   OR data_type = 'bigint'\n" +
                "                   THEN\n" +
                "                   NUMERIC_PRECISION\n" +
                "               ELSE\n" +
                "                   CHARACTER_MAXIMUM_LENGTH\n" +
                "               END\n" +
                "           )            AS rows \n" +
                "FROM INFORMATION_SCHEMA.Columns \n" +
                "WHERE table_name='"+table+"' AND table_schema='"+sysDataSource.getEnname()+"'";
        return DBUtilsController.queryAllStudentTable(sql,sysDataSource);
    }
  • 4
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
由于篇幅较长,我只能提供代码示例,希望对你有所帮助。 使用JDBC实现: User类: ```java public class User { private int id; private String name; private String password; private String email; public User(int id, String name, String password, String email) { this.id = id; this.name = name; this.password = password; this.email = email; } // getter and setter methods } ``` JDBCUtils工具类: ```java public class JDBCUtils { private static final String URL = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC"; private static final String USER = "root"; private static final String PASSWORD = "password"; public static Connection getConnection() throws SQLException { return DriverManager.getConnection(URL, USER, PASSWORD); } public static void close(Connection conn, Statement stmt, ResultSet rs) { try { if (rs != null) { rs.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (stmt != null) { stmt.close(); } } catch (SQLException e) { e.printStackTrace(); } try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } ``` UserDao类: ```java public class UserDao { public void insert(User user) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JDBCUtils.getConnection(); String sql = "INSERT INTO t_user(name, password, email) VALUES (?, ?, ?)"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getName()); pstmt.setString(2, user.getPassword()); pstmt.setString(3, user.getEmail()); int rows = pstmt.executeUpdate(); System.out.println("Inserted " + rows + " row(s)."); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(conn, pstmt, null); } } public void update(User user) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JDBCUtils.getConnection(); String sql = "UPDATE t_user SET name=?, password=?, email=? WHERE id=?"; pstmt = conn.prepareStatement(sql); pstmt.setString(1, user.getName()); pstmt.setString(2, user.getPassword()); pstmt.setString(3, user.getEmail()); pstmt.setInt(4, user.getId()); int rows = pstmt.executeUpdate(); System.out.println("Updated " + rows + " row(s)."); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(conn, pstmt, null); } } public void delete(int id) { Connection conn = null; PreparedStatement pstmt = null; try { conn = JDBCUtils.getConnection(); String sql = "DELETE FROM t_user WHERE id=?"; pstmt = conn.prepareStatement(sql); pstmt.setInt(1, id); int rows = pstmt.executeUpdate(); System.out.println("Deleted " + rows + " row(s)."); } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(conn, pstmt, null); } } public List<User> queryAll() { List<User> userList = new ArrayList<>(); Connection conn = null; Statement stmt = null; ResultSet rs = null; try { conn = JDBCUtils.getConnection(); String sql = "SELECT id, name, password, email FROM t_user"; stmt = conn.createStatement(); rs = stmt.executeQuery(sql); while (rs.next()) { int id = rs.getInt("id"); String name = rs.getString("name"); String password = rs.getString("password"); String email = rs.getString("email"); User user = new User(id, name, password, email); userList.add(user); } } catch (SQLException e) { e.printStackTrace(); } finally { JDBCUtils.close(conn, stmt, rs); } return userList; } } ``` 测试类Test1: ```java public class Test1 { public static void main(String[] args) { UserDao userDao = new UserDao(); // insert User user1 = new User(0, "Alice", "123456", "alice@example.com"); userDao.insert(user1); User user2 = new User(0, "Bob", "abcdef", null); userDao.insert(user2); // update User user3 = new User(1, "Alice2", "654321", "alice2@example.com"); userDao.update(user3); // queryAll List<User> userList = userDao.queryAll(); for (User user : userList) { System.out.println(user.getId() + "\t" + user.getName() + "\t" + user.getPassword() + "\t" + user.getEmail()); } // delete userDao.delete(2); } } ``` 使用C3P0实现: C3P0Utils工具类: ```java public class C3P0Utils { private static ComboPooledDataSource dataSource = new ComboPooledDataSource(); public static DataSource getDataSource() { return dataSource; } } ``` C3P0UserDao类: ```java public class C3P0UserDao { private QueryRunner runner = new QueryRunner(C3P0Utils.getDataSource()); public void insert(User user) { String sql = "INSERT INTO t_user(name, password, email) VALUES (?, ?, ?)"; try { int rows = runner.update(sql, user.getName(), user.getPassword(), user.getEmail()); System.out.println("Inserted " + rows + " row(s)."); } catch (SQLException e) { e.printStackTrace(); } } public void update(User user) { String sql = "UPDATE t_user SET name=?, password=?, email=? WHERE id=?"; try { int rows = runner.update(sql, user.getName(), user.getPassword(), user.getEmail(), user.getId()); System.out.println("Updated " + rows + " row(s)."); } catch (SQLException e) { e.printStackTrace(); } } public void delete(int id) { String sql = "DELETE FROM t_user WHERE id=?"; try { int rows = runner.update(sql, id); System.out.println("Deleted " + rows + " row(s)."); } catch (SQLException e) { e.printStackTrace(); } } public List<User> queryAll() { String sql = "SELECT id, name, password, email FROM t_user"; try { return runner.query(sql, new BeanListHandler<>(User.class)); } catch (SQLException e) { e.printStackTrace(); } return null; } } ``` 测试类Test2: ```java public class Test2 { public static void main(String[] args) { C3P0UserDao userDao = new C3P0UserDao(); // insert User user1 = new User(0, "Alice", "123456", "alice@example.com"); userDao.insert(user1); User user2 = new User(0, "Bob", "abcdef", null); userDao.insert(user2); // update User user3 = new User(1, "Alice2", "654321", "alice2@example.com"); userDao.update(user3); // queryAll List<User> userList = userDao.queryAll(); for (User user : userList) { System.out.println(user.getId() + "\t" + user.getName() + "\t" + user.getPassword() + "\t" + user.getEmail()); } // delete userDao.delete(2); } } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值