jdbc -5- 使用 JDBC 驱动程序处理元数据 - 自定义JDBCTOOLS(通用查询方法,可返回不同类的对象)

DatabaseMetaData

Java 通过JDBC获得连接以后,得到一个Connection 对象,可以从这个对象获得有关数据库管理系统的各种信息,
包括数据库中的各个表,表中的各个列,数据类型,触发器,存储过程等各方面的信息。
根据这些信息,JDBC可以访问一个实现事先并不了解的数据库。

获取这些信息的方法都是在DatabaseMetaData类的对象上实现的,而DataBaseMetaData对象是在Connection对象上获得的。

DatabaseMetaData 类中提供了许多方法用于获得数据源的各种信息,通过这些方法可以非常详细的了解数据库的信息:

getURL():返回一个String类对象,代表数据库的URL。
getUserName():返回连接当前数据库管理系统的用户名。
isReadOnly():返回一个boolean值,指示数据库是否只允许读操作。
getDatabaseProductName():返回数据库的产品名称。
getDatabaseProductVersion():返回数据库的版本号。
getDriverName():返回驱动驱动程序的名称。
getDriverVersion():返回驱动程序的版本号。

ResultSetMetaDate

可用于获取关于 ResultSet 对象中列的类型和属性信息的对象:
getColumnName(int column):获取指定列的名称
getColumnCount():返回当前 ResultSet 对象中的列数。
getColumnTypeName(int column):检索指定列的数据库特定的类型名称。
getColumnDisplaySize(int column):指示指定列的最大标准宽度,以字符为单位。
isNullable(int column):指示指定列中的值是否可以为 null。
isAutoIncrement(int column):指示是否自动为指定列进行编号,这样这些列仍然是只读的。

jdbcTools

实现连接数据库的常用方法包括更新,查询(返回对象)的通用方法

package connect;


import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.sql.*;
import java.sql.ResultSet;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

/*
操作JDBC的工具类,其中封装了一些工具方法
version 1
 */
public class JDBCTools {
    private static Connection connection = null;
    private static Statement statement = null;

    //连接数据库
    public static void applyConnnect(){
        //读取类路径下的jdbc.properties
        try {
            InputStream resourceAsStream = DriverConnection.class.getClassLoader().getResourceAsStream("jdbc.properties");

            Properties properties1 = new Properties();
            properties1.load(resourceAsStream);

            String driverClass = properties1.getProperty("driver");
            String jdbcUrl = properties1.getProperty("jdbcUrl");
           // String user = properties1.getProperty("user");
           // String password = properties1.getProperty("password");

            java.sql.Driver driver = (java.sql.Driver) Class.forName(driverClass).newInstance();

            //Properties properties = new Properties();
            //properties.put("user",user);
            //properties.put("password",password);

            connection = driver.connect(jdbcUrl, properties1);
            statement = connection.createStatement();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    private JDBCTools(){}
    static {
        applyConnnect();
    }

    //获取连接
    public static Connection getConnection(){
        if (connection == null)
            applyConnnect();
        return connection;
    }

    //获取Statement
    public  static Statement getStatement(){
        if (statement == null)
            applyConnnect();
        return statement;
    }

    //关闭Statement和Connection
    public static void disConnect(Statement statement, Connection connection, ResultSet resultSet){
        try {
            if (statement != null)
                statement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (connection != null)
                connection.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }finally {
                try {
                    if (resultSet != null)
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
    }
    public static void disConnect(){
        try {
            connection.close();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                statement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    //`````````````````````````````````通过statement对象进行的操作`````````````````````````````````
    //执行更新操作
    public static void Update(String sql){
        try {
            getStatement().executeUpdate(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    //查询操作
    public static ResultSet Check(String sql) {
        ResultSet resultSet = null;
        try {
            resultSet = getStatement().executeQuery(sql);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return resultSet;


    }

    //······································通过PreparedStatement进行操作··················································
    public static void P_Update(String sql, Object ... args){
        try {
            PreparedStatement preparedStatement = connection.prepareStatement(sql);
            int i = 1;
            for (Object o: args) {
                preparedStatement.setObject(i,o);
                i++;
            }
            preparedStatement.executeUpdate();
            preparedStatement.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    public static void instance_insert(CustomerClass customerClass){
        PreparedStatement preparedStatement = null;
        try {
            String sql = "INSERT INTO customer (name, email, brith) VALUES (?,?,?)";
            preparedStatement = connection.prepareStatement(sql);
            preparedStatement.setObject(1,customerClass.getName());
            preparedStatement.setObject(2,customerClass.getEmail());
            preparedStatement.setObject(3,customerClass.getDate());
            preparedStatement.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            try {
                if (preparedStatement != null)
                    preparedStatement.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
    //通用查询方法(返回对象)
    public  static <T>  T instance_search(Class<T> clazz, String sql,Object... args){
        T entity = null;
        int i = 1;
        try {
            //初始化PreparedStatement
            PreparedStatement preparedStatement = getConnection().prepareStatement(sql);
            for (Object o: args) {
                preparedStatement.setObject(i,o);
                i++;
            }

            //获得返回参数集
            ResultSet resultSet = preparedStatement.executeQuery();

            //得到ResultSetMeteData(getColumnCount,getColumnLabel)
            ResultSetMetaData metaData = resultSet.getMetaData();

            //把SQL中的别名及返回集中的值放入Map(别名=值)中(通过解析SQL语句来判断)(SQL语句中要有别名)
            HashMap<String, Object> map = new HashMap<>();
            while (resultSet.next()){
                for ( i = 1; i <=metaData.getColumnCount() ; i++) {
                    String columnLabel = metaData.getColumnLabel(i);
                    Object object = resultSet.getObject(i);
                    map.put(columnLabel,object);
                }

            }
            //通过反射创建对象
            if (map.size()>0)
            entity = clazz.newInstance();
            //通过map及反射为对象赋值
            for (Map.Entry<String,Object> entry : map.entrySet()) {
                String fieldName = entry.getKey();
                Object fieldValue = entry.getValue();
                Field declaredField = clazz.getDeclaredField(fieldName);
                declaredField.setAccessible(true);
                declaredField.set(entity,fieldValue);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {

        }
        return entity;
    }


}
/*
doc:
1.查询:SELECT id ,name, email, brith FROM customer(SELECT id ,name, email, brith FROM customer WHERE id = ?)
2.update:UPDATE customer SET name = 'arli' WHERE id = 2
3.delete:DELETE FROM customer WHERE id= ?
4.insert: INSERT INTO customer (name, email, brith) VALUES('WWW','asdfsf.com','seg-654-46')
4.insert:INSERT INTO customer (name, email, brith) VALUES (?,?,?)   (用于preparedStatement更新)
 */


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值