JDBC常用方法连接MySQL数据库 连接Oracle数据库 插入数据 查找表 删除多个指定表 动态插入数据 删除数据 查询该表所有数据 显示表的结构

package jdbc.base;

import java.sql.*;

/**
 * 参考资料:https://blog.csdn.net/u010297791/article/details/52637868
 * <p>
 * 操作的一般过程
 * <p>
 * <p>
 * 1、连接数据库
 * <p>
 * 2、调用Class.forName()方法加载驱动程序。
 * <p>
 * 3、调用DriverManager对象的getConnection()方法,获得一个Connection对象。
 * <p>
 * 4、创建一个Statement对象,准备一个SQL语句,这个SQL语句可以是Statement对象(立即执行的的语句)、PreparedStatement语句(预编译的语句)或CallableStatement对象(存储过程调用的语句)。
 * <p>
 * 5、调用excuteQuery()等方法执行SQL语句,并将结果保存在ResultSet对象;或者调用executeUpdate()等方法执行SQL语句,不返回ResultSet对象的结果。
 * <p>
 * 6、对返回的ResultSet对象进行显示等相当的处理。
 * <p>
 * 7、释放资源。
 * <p>
 * 方法:
 * Statement系列对象.executeUpdate(sql) 执行:insert delete update alter create drop等DDL、DML语句
 * Statement系列对象.executeQuery(sql) 执行:select DQL语句 返回:ResultSet结果集对象
 */
class JdbcDemo {
    private static Connection con;//与特定数据库的连接(会话)的变量con
    private static Statement stmt; //用stmt 来执行静态SQL语句
    private static PreparedStatement pstmt;//用pstmt 来执行动态SQL语句,防SQL攻击 !注意pstmt.setString时,自带'',查询、删除表名时候不要这样用
    private static ResultSet rs;//结果集
    private static String sql;//sql语句, 无需加";"

    public static void main(String[] args) throws SQLException, ClassNotFoundException {
        conectionMysql();//连接MySQL数据库
//        conectionOracle();//连接Oracle数据库
//        insertValue();//插入数据
//        searchTables();//查找表
//        dropTable("table1");//删除多个指定表
        createTable("table3", "table2");//创建表   表结构一样
//        insertValue2();//动态插入数据
//        deleteValue();//删除数据
//        selectValues("nametb");//查询该表所有数据
//        showTableDescribe("table1");//显示表的结构
//        showColumnType("table1");//显示该表列信息

        //关闭连接:关闭顺序与声明相反
        if (!rs.isClosed()) {
            rs.close();//关闭记录集
        }
        if (!stmt.isClosed()) {
            stmt.close();//关闭用来执行SQL语句的声明
        }
        if (!con.isClosed()) {
            con.close();//关闭连接对象
        }
    }

    //显示列信息
    private static void showColumnType(String table) throws SQLException {
        sql = "SELECT *  FROM " + table;
        PreparedStatement stmt2 = (PreparedStatement) con.prepareStatement(sql);
        rs = stmt2.executeQuery(sql);
        ResultSetMetaData data = rs.getMetaData();
        while (rs.next()) {
            for (int i = 1; i <= data.getColumnCount(); i++) {
                //获得所有列的数目及实际列数
                int columnCount = data.getColumnCount();
                //获得指定列的列名
                String columnName = data.getColumnName(i);
                //获得指定列的列值
                String columnValue = rs.getString(i);
                //获得指定列的数据类型
                int columnType = data.getColumnType(i);
                //获得指定列的数据类型名
                String columnTypeName = data.getColumnTypeName(i);
                //所在的Catalog名字
                String catalogName = data.getCatalogName(i);
                //对应数据类型的类
                String columnClassName = data.getColumnClassName(i);
                //在数据库中类型的最大字符个数
                int columnDisplaySize = data.getColumnDisplaySize(i);
                //默认的列的标题
                String columnLabel = data.getColumnLabel(i);
                //获得列的模式
                String schemaName = data.getSchemaName(i);
                //某列类型的精确度(类型的长度)
                int precision = data.getPrecision(i);
                //小数点后的位数
                int scale = data.getScale(i);
                //获取某列对应的表名
                String tableName = data.getTableName(i);
                // 是否自动递增
                boolean isAutoInctement = data.isAutoIncrement(i);
                //在数据库中是否为货币型
                boolean isCurrency = data.isCurrency(i);
                //是否为空
                int isNullable = data.isNullable(i);
                //是否为只读
                boolean isReadOnly = data.isReadOnly(i);
                //能否出现在where中
                boolean isSearchable = data.isSearchable(i);
                System.out.println(columnCount);
                System.out.println("获得列" + i + "的字段名称:" + columnName);
                System.out.println("获得列" + i + "的字段值:" + columnValue);
                System.out.println("获得列" + i + "的类型,返回SqlType中的编号:" + columnType);
                System.out.println("获得列" + i + "的数据类型名:" + columnTypeName);
                System.out.println("获得列" + i + "所在的Catalog名字:" + catalogName);
                System.out.println("获得列" + i + "对应数据类型的类:" + columnClassName);
                System.out.println("获得列" + i + "在数据库中类型的最大字符个数:" + columnDisplaySize);
                System.out.println("获得列" + i + "的默认的列的标题:" + columnLabel);
                System.out.println("获得列" + i + "的模式:" + schemaName);
                System.out.println("获得列" + i + "类型的精确度(类型的长度):" + precision);
                System.out.println("获得列" + i + "小数点后的位数:" + scale);
                System.out.println("获得列" + i + "对应的表名:" + tableName);
                System.out.println("获得列" + i + "是否自动递增:" + isAutoInctement);
                System.out.println("获得列" + i + "在数据库中是否为货币型:" + isCurrency);
                System.out.println("获得列" + i + "是否为空:" + isNullable);
                System.out.println("获得列" + i + "是否为只读:" + isReadOnly);
                System.out.println("获得列" + i + "能否出现在where中:" + isSearchable);
            }
        }
        rs.close();
        stmt2.close();
    }

    //显示表的结构
    private static void showTableDescribe(String tableName) throws SQLException {
        sql = "SHOW CREATE TABLE " + tableName;
        rs = stmt.executeQuery(sql);
        while (rs.next()) {
            for (int i = 1; i <= 2; i++) {
                System.out.println(rs.getObject(i));
            }
        }
        rs.close();
    }

    //查询数据
    private static void selectValues(String tableName) throws SQLException {
        sql = "SELECT *  FROM " + tableName;
        rs = stmt.executeQuery(sql);
        /*
        * MySQL生效
//        while (rs.next()) {//判断下一行是否有值(rs光标从列名行开始)
//            System.out.println(rs.getInt(1) + "\t\t" + rs.getString(2));
//            System.out.println(rs.getObject(1) + "\t\t" + rs.getObject("name"));
//        }
        //将结果集光标放置第一行前面
//        rs.beforeFirst();
        * */

        System.out.println("通用遍历:");
        //获取列数
        int count = rs.getMetaData().getColumnCount();
        while (rs.next()) {//遍历行
            for (int i = 1; i <= count; i++) {//遍历列
                System.out.print(rs.getString(i));
                if (i < count) {
                    System.out.print("\t");
                }
            }
            System.out.println();
        }
    }

    //删除数据
    private static void deleteValue() throws SQLException {
        sql = "DELETE FROM table1 WHERE id = ?";
        pstmt = con.prepareStatement(sql);
        pstmt.setInt(1, 1);//第一个号位置的值为1
        pstmt.executeUpdate();
        pstmt.close();
    }

    //动态插入数据
    private static void insertValue2() throws SQLException {
        sql = "INSERT INTO table1 VALUES(?, ?);";//用preparedStatement预处理来执行sql语句
        pstmt = con.prepareStatement(sql);//创建一个 PreparedStatement 对象来将参数化的 SQL 语句发送到数据库。
        pstmt.setInt(1, 100);//第一个?号位置的值为100
        pstmt.setString(2, "阿基米德");//第二个?号位置的值为"阿基米德"
        System.out.println(pstmt);//生成的sql语言中,字符串自带分号,不需要加''
        pstmt.executeUpdate(); //参数准备后执行语句            查询executeQuery()
        pstmt.close();
    }

    //插入数据
    private static void insertValue() throws SQLException {
        sql = "INSERT INTO table2 VALUES(1, '爱因斯坦')";
        int r = stmt.executeUpdate(sql);
        System.out.println("影响行数:" + r);
    }

    //创建表
    private static void createTable(String... tableNames) throws SQLException {
        for (String tableName : tableNames) {
            sql = "create table if not exists " + tableName + "(" +
                    "id int comment '学号'," +
                    "name varchar(20) comment '名字'," +
                    "primary key(id, name)" +
                    ")character set utf8, collate utf8_general_ci, comment = '用于MysqlTest类测试使用'";
            System.out.println(sql);
            stmt.executeUpdate(sql);
        }
    }

    //删除指定表
    private static void dropTable(String... tableNames) throws SQLException {
        for (String tableName : tableNames) {
            sql = "DROP TABLE " + tableName;
            System.out.println(sql);
            stmt.executeUpdate(sql);
        }
    }

    //查找表
    private static void searchTables() throws SQLException {
        sql = "SHOW TABLES";
        //执行并返回结果
        rs = stmt.executeQuery(sql);
        System.out.println("该数据库拥有的所有表和视图:");
        while (rs.next()) {
            System.out.println(rs.getString(1));
        }
        rs.close();
    }

    //连接MySQL数据库并初始化
    private static void conectionMysql() throws SQLException, ClassNotFoundException {
        //1.加载驱动类
        Class.forName("com.mysql.jdbc.Driver");
        //2.获得与特定数据库的连接(会话)的变量con
        con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc" +
                //useServerPrepStmts=true&cachePrepStmts=true   开启预处理功能并缓存
                "?useServerPrepStmts=true&cachePrepStmts=true&" +
                "useUnicode=true&amp&" +
                "characterEncoding=UTF-8", "root", "root");
        if (!con.isClosed()) {
            System.out.println("成功连接到MySQL数据库!");
        }
        stmt = con.createStatement();//获得Statement 对象

        /*ClassNotFoundException   未导入驱动包,类名打错
         * SQLException     端口号数据库名账号密码错误,未开启服务*/
    }

    //连接MySQL数据库并初始化
    private static void conectionOracle() throws SQLException, ClassNotFoundException {
        //1.加载驱动
        Class.forName("oracle.jdbc.driver.OracleDriver");
        //2.得到连接
        con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.75.128:1521:orcl", "scott", "tiger");
        if (!con.isClosed()) {
            System.out.println("成功连接到Oracle数据库!");
        }
        stmt = con.createStatement();//获得Statement 对象
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值