Native Jdbc gets libraries, tables, and fields


1. Introduction

1 Overview

  • JDBC (Java Database Connectivity) is a public interface (a set of APIs) that is independent of a specific database management system and common SQL database access and operation, and defines a standard Java class library for accessing databases, ( java.sql,javax .sql ) use these class libraries to conveniently access database resources in a standard way.
  • JDBC provides a unified way to access different databases , and shields some details for developers.
  • The goal of JDBC is to enable Java programmers to use JDBC to connect to any database system that provides a JDBC driver , so that programmers do not need to have too much understanding of the characteristics of a specific database system, thus greatly simplifying and speeding up the development process.

insert image description here

2. Jdbc gets the connection

insert image description here

  • 1. Load the driver
  • 2. Establish a connection
  • 3. Create a Statement object
  • 4. Execute SQL
  • 5. Close the connection
String jdbcdriver = "";
String url = "";
String username = "";
String password = "";
String sql = "";
//    1、加载驱动
Class.forName(jdbcdriver);
//    2、建立连接
Connection conn = DriverManager.getConnection(url, username, password);
//    3、创建Statement对象
PreparedStatement ps = conn.prepareStatement(sql);
//    4、执行SQL
ps.executeQuery();
//    5、关闭连接
conn.close();
ps.close();
closeConn(conn, ps);

3. Actuator

There are three interfaces in the java.sql package that define different ways of calling the database:

  • Statement: An object used to execute a static SQL statement and return the results it generates.
  • PrepatedStatement: The SQL statement is precompiled and stored in this object, which can be used to efficiently execute the statement multiple times.
  • CallableStatement: Used to execute SQL stored procedures

insert image description here

2. Get the link

1. Get the link

 //    1、加载驱动
 Class.forName(jdbcdriver);
 //    2、建立连接
 Connection conn = DriverManager.getConnection(url, username, password);

2. Close the connection

//    5、关闭连接
conn.close();
ps.close();
closeConn(conn, ps);
public static <T> void close(T... t) {
    
    
    for (T one : t) {
    
    
        if (one instanceof AutoCloseable) {
    
    
            try {
    
    
                ((AutoCloseable) one).close();
            } catch (Exception e) {
    
    
                e.printStackTrace();
            }
        }
    }
}

Method 2:

/**
 * 
 * @Description 关闭资源操作
 * @author shkstart
 * @date 上午10:21:15
 * @param conn
 * @param ps
 * @param rs
 */
public static void closeResource(Connection conn,Statement ps,ResultSet rs){
    
    
	try {
    
    
		if(ps != null)
			ps.close();
	} catch (SQLException e) {
    
    
		e.printStackTrace();
	}
	try {
    
    
		if(conn != null)
			conn.close();
	} catch (SQLException e) {
    
    
		e.printStackTrace();
	}
	try {
    
    
		if(rs != null)
			rs.close();
	} catch (SQLException e) {
    
    
		e.printStackTrace();
	}
}

3、Statement

Statement: An object used to execute a static SQL statement and return the results it generates.

However, there are disadvantages in using Statement to operate data tables:

  • Problem 1: There is a string operation, which is cumbersome
  • Problem 2: There is a SQL injection problem
// 1、加载驱动
Class.forName(driverClass);
// 2、获取连接
Connection conn = DriverManager.getConnection(url, user, password);
//	3、获取执行器
Statement st = conn.createStatement();
//	4、执行查询
ResultSet rs = st.executeQuery(sql);
//	5、获取结果集的元数据
ResultSetMetaData rsmd = rs.getMetaData();

4、PrepatedStatement

PrepatedStatement: The SQL statement is precompiled and stored in this object, which can be used to efficiently execute the statement multiple times.

  • The PreparedStatement object can be obtained by calling the preparedStatement(String sql) method of the Connection object

  • The PreparedStatement interface is a subinterface of Statement, which represents a precompiled SQL statement

  • The parameters in the SQL statement represented by the PreparedStatement object are represented by question marks (?), call the setXxx() method of the PreparedStatement object to set these parameters. The setXxx() method has two parameters, the first parameter is the SQL statement to be set The index (starting from 1) of the parameter in the second is the value of the parameter in the set SQL statement

Use PreparedStatement to realize add, delete and change operations

//通用的增、删、改操作(体现一:增、删、改 ; 体现二:针对于不同的表)
	public void update(String sql,Object ... args){
    
    
		Connection conn = null;
		PreparedStatement ps = null;
		try {
    
    
			//1.获取数据库的连接
			conn = JDBCUtils.getConnection();
			
			//2.获取PreparedStatement的实例 (或:预编译sql语句)
			ps = conn.prepareStatement(sql);
			//3.填充占位符
			for(int i = 0;i < args.length;i++){
    
    
				ps.setObject(i + 1, args[i]);
			}
			
			//4.执行sql语句
			ps.execute();
		} catch (Exception e) {
    
    
			
			e.printStackTrace();
		}finally{
    
    
			//5.关闭资源
			JDBCUtils.closeResource(conn, ps);
			
		}
	}

Use PreparedStatement to implement query operations


5、 ResultSet

Question 1: After getting the result set, how to know which columns are in the result set? What are the column names?

​ Need to use an object describing ResultSet, namely ResultSetMetaData

insert image description here

  • The query needs to call the executeQuery() method of PreparedStatement, and the query result is a ResultSet object

  • The ResultSet object encapsulates the result set of performing database operations in the form of a logical table, and the ResultSet interface is provided and implemented by the database manufacturer

  • What ResultSet returns is actually a data table. There is a pointer pointing to the front of the first record of the data table.

  • The ResultSet object maintains a cursor pointing to the current data row . Initially, the cursor is before the first row, and can be moved to the next row through the next() method of the ResultSet object. Call the next() method to check whether the next line is valid. If valid, the method returns true and the pointer moves down. Equivalent to the combination of the hasNext() and next() methods of the Iterator object.

  • When the pointer points to a row, you can get the value of each column by calling getXxx(int ​​index) or getXxx(int ​​columnName).

    • Example: getInt(1), getString("name")
    • Note: The indexes in the related Java APIs involved in the interaction between Java and the database start from 1.
  • Common methods of the ResultSet interface:

    • boolean next()

    • getString()

    insert image description here

6、ResultSetMetaData

An object used to obtain information about the types and properties of the columns in the ResultSet object

ResultSetMetaData meta = rs.getMetaData( );
  • getColumnName(int column): Get the name of the specified column.
  • getColumnLabel(int column): Get the alias of the specified column.
  • getColumnCount(): Returns the number of columns in the current ResultSet object.
  • getColumnTypeName(int column): Retrieves the database-specific type name for the specified column.
  • getColumnDisplaySize(int column): Indicates the maximum standard width of the specified column, in characters.
  • isNullable(int column): Indicates whether the value in the specified column can be null.
  • isAutoIncrement(int column): Indicates whether to automatically number the specified columns so that they remain read-only.

insert image description here

3. Execute SQL

2.1 Add/Delete/Modify

	//通用的增、删、改操作(体现一:增、删、改 ; 体现二:针对于不同的表)
	public void update(String sql,Object ... args){
    
    
		Connection conn = null;
		PreparedStatement ps = null;
		try {
    
    
			//1.获取数据库的连接
			conn = JDBCUtils.getConnection();
			
			//2.获取PreparedStatement的实例 (或:预编译sql语句)
			ps = conn.prepareStatement(sql);
			//3.填充占位符
			for(int i = 0;i < args.length;i++){
    
    
				ps.setObject(i + 1, args[i]);
			}
			
			//4.执行sql语句
			ps.execute();
		} catch (Exception e) {
    
    
			
			e.printStackTrace();
		}finally{
    
    
			//5.关闭资源
			JDBCUtils.closeResource(conn, ps);
			
		}
	}

2.2 Query

Use PreparedStatement to implement query operations

// 通用的针对于不同表的查询:返回一个对象 (version 1.0)
	public <T> T getInstance(Class<T> clazz, String sql, Object... args) {
    
    

		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
    
    
			// 1.获取数据库连接
			conn = JDBCUtils.getConnection();

			// 2.预编译sql语句,得到PreparedStatement对象
			ps = conn.prepareStatement(sql);

			// 3.填充占位符
			for (int i = 0; i < args.length; i++) {
    
    
				ps.setObject(i + 1, args[i]);
			}

			// 4.执行executeQuery(),得到结果集:ResultSet
			rs = ps.executeQuery();

			// 5.得到结果集的元数据:ResultSetMetaData
			ResultSetMetaData rsmd = rs.getMetaData();

			// 6.1通过ResultSetMetaData得到columnCount,columnLabel;通过ResultSet得到列值
			int columnCount = rsmd.getColumnCount();
			if (rs.next()) {
    
    
				T t = clazz.newInstance();
				for (int i = 0; i < columnCount; i++) {
    
    // 遍历每一个列

					// 获取列值
					Object columnVal = rs.getObject(i + 1);
					// 获取列的别名:列的别名,使用类的属性名充当
					String columnLabel = rsmd.getColumnLabel(i + 1);
					// 6.2使用反射,给对象的相应属性赋值
					Field field = clazz.getDeclaredField(columnLabel);
					field.setAccessible(true);
					field.set(t, columnVal);

				}

				return t;

			}
		} catch (Exception e) {
    
    

			e.printStackTrace();
		} finally {
    
    
			// 7.关闭资源
			JDBCUtils.closeResource(conn, ps, rs);
		}

		return null;

	}

4. Get library and table structure

1. Get Catalog

/**
 * 获取catalog
 *
 * @param jdbcdriver 驱动类(DriverClass)(com.mysql.cj.jdbc.Driver)
 * @param url        地址(jdbc:mysql://10.20.30.40:3306)
 * @param username   用户名
 * @param password   密码
 */
public List<String> getCatalogs(String jdbcdriver, String url, String username, String password) throws ClassNotFoundException, SQLException {
    
    
    ArrayList<String> list = new ArrayList<>();
    //    1、加载驱动
    Class.forName(jdbcdriver);
    //    2、建立连接
    Connection conn = DriverManager.getConnection(url, username, password);
    try {
    
    
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet resultSet = metaData.getCatalogs();
        while (resultSet.next()) {
    
    
            String string = resultSet.getString("TABLE_CAT");
            list.add(string);
        }
    } catch (SQLException e) {
    
    
        e.printStackTrace();
    } finally {
    
    
        conn.close();
    }
    return list;
}

2. Get library list

/**
 * 获取数据库
 *
 * @param jdbcdriver 驱动类(DriverClass)(com.mysql.cj.jdbc.Driver)
 * @param url        地址(jdbc:mysql://10.20.30.40:3306)
 * @param username   用户名
 * @param password   密码
 * @param catalogs   catalogs
 */
public List<String> getDatabase(String jdbcdriver, String url, String username, String password, String catalogs) throws ClassNotFoundException, SQLExcepti
    ArrayList<String> list = new ArrayList<>();
    //    1、加载驱动
    Class.forName(jdbcdriver);
    //    2、建立连接
    Connection conn = DriverManager.getConnection(url, username, password);
    try {
    
    
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet resultSet = metaData.getSchemas(catalogs, null);
        //  没有catalog可以采用下面这种方式
        //  ResultSet resultSet = metaData.getSchemas();
        while (resultSet.next()) {
    
    
            String string = resultSet.getString("TABLE_SCHEM");
            list.add(string);
        }
    } catch (SQLException e) {
    
    
        e.printStackTrace();
    } finally {
    
    
        conn.close();
    }
    return list;
}

3. Get the table name

/**
 * 获取表
 *
 * @param jdbcdriver 驱动类(DriverClass)(com.mysql.cj.jdbc.Driver)
 * @param url        地址(jdbc:mysql://10.20.30.40:3306)
 * @param username   用户名
 * @param password   密码
 * @param catalogs   catalogs
 * @param database   数据库
 */
public List<String> getTables(String jdbcdriver, String url, String username, String password, String catalogs, String database) throws ClassNotFoundException, SQLException {
    
    
    List<String> list = new ArrayList<>();
    //    1、加载驱动
    Class.forName(jdbcdriver);
    //    2、建立连接
    Connection conn = DriverManager.getConnection(url, username, password);
    try {
    
    
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet tables = metaData.getTables(
                catalogs,
                database,
                "%",
                new String[]{
    
    "TABLE", "VIEW"});
        while (tables.next()) {
    
    
            String name = tables.getString("TABLE_NAME");
            list.add(name);
        }
    } catch (SQLException e) {
    
    
        e.printStackTrace();
    } finally {
    
    
        conn.close();
    }
    return list;
}

4. Get fields

/**
 * 获取字段
 *
 * @param jdbcdriver 驱动类(DriverClass)(com.mysql.cj.jdbc.Driver)
 * @param url        地址(jdbc:mysql://10.20.30.40:3306)
 * @param username   用户名
 * @param password   密码
 * @param catalogs   catalogs
 * @param database   库
 * @param table      表
 */
public List<JSONObject> getColumns(String jdbcdriver, String url, String username, String password, String catalogs, String database) throws ClassNotFoundException, SQLException {
    
    
    List<JSONObject> list = new ArrayList<>();
    //    1、加载驱动
    Class.forName(jdbcdriver);
    //    2、建立连接
    Connection conn = DriverManager.getConnection(url, username, password);
    try {
    
    
        DatabaseMetaData metaData = conn.getMetaData();
        ResultSet rs = metaData.getColumns(catalogs, database, table, "%");
        while (rs.next()) {
    
    
            JSONObject json = new JSONObject();
            //  列明
            json.put("columnName", rs.getString("COLUMN_NAME"));
            //  列类型
            json.put("typeName", rs.getString("TYPE_NAME"));
            //  列备注
            json.put("remarks", rs.getString("REMARKS"));
            list.add(json);
        }
    } catch (Exception e) {
    
    
        e.printStackTrace();
    } finally {
    
    
        conn.close();
    }
    return list;
}

Guess you like

Origin blog.csdn.net/weixin_44624117/article/details/131335217