MySQL JDBC

 一、连接MySQL数据库

1.  MySQL JDBC四大参数

private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1:3306/local_test?characterEncoding=UTF-8&useSSL=false";
private static String userName = "root";
private static String passWord = "mysqlpasswd";

2.  全局变量

private static Logger logger = LogManager.getLogger(MysqlJdbc.class);

private static Connection connection;
private static Statement statement;
private static ResultSet resultSet;

 3.  连接数据库

static {
    try {
        // 加载驱动
        Class.forName(DRIVER);
        // 创建链接
        connection = DriverManager.getConnection(URL, USER_NAME, PASSWORD);
        // 访问数据库
        statement = connection.createStatement();
    } catch (ClassNotFoundException | SQLException e) {
        e.printStackTrace();
        logger.error("数据库连接失败!");
    }
}

 4.  Statement类

  • executeQuery方法
    • 执行SQL查询
    • 返回ResultSet对象
  • executeUpdate方法
    • 可执行增、删、改
    • 返回执行受到影响的行数
  • execute方法
    • 可执行任何SQL语句
    • 返回一个布尔值

5.  资源释放

public static void release() {
    try {
        if (connection != null)
            connection.close();
        if (statement != null)
            statement.close();
        if (resultSet != null)
            resultSet.close();
    } catch (SQLException e) {
        e.printStackTrace();
    }
}

二、MySQL CRUD

1.  判断表是否存在

public static boolean whetherExistsTable(String table) {
    boolean tableFound = false;
    try {
        final ResultSet resultSet = statement.executeQuery("SHOW TABLES");
        while (resultSet.next()) {
            if (resultSet.getString(1).toUpperCase().equals(table.toUpperCase().trim())) {
                tableFound = true;
                break;
            }
        }
        if (!tableFound) {
            logger.info("数据表不存在!");
        }
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("SQL语法错误!");
    }
    return tableFound;
}

2.  获取表字段

public static List<String> describeTable(String table) {
    List<String> list = new ArrayList<>();
    try {
        if (whetherExistsTable(table)) {
            resultSet = statement.executeQuery("DESCRIBE " + table);
            while (resultSet.next()) {
                list.add(resultSet.getString(1));
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("SQL语法错误!");
    }
    return list;
}

3.  查询操作

public static List<Map<String, Object>> selectTable(String table, String sql) {
    List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
    Map<String, Object> map = null;

    try {
        if (whetherExistsTable(table)) {
            List<String> listDescribe = describeTable(table);
            resultSet = statement.executeQuery(sql);

            while (resultSet.next()) {
                map = new HashMap<>();
                for (String str : listDescribe) {
                    map.put(str, resultSet.getObject(str));
                }
                list.add(map);
            }
        }
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("SQL语法错误!");
    }
    return list;
}

4.  增加操作

public static String addTable(String table, String sql) {
    String result = "";
    int execute = 0;
    try {
        if (whetherExistsTable(table)) {
            StringBuilder addSql = new StringBuilder();
            addSql.append("INSERT INTO " + table + "(");

            List<String> listDescribe = describeTable(table);
            String values = "";
            for (String str : listDescribe) {
                values += str;
                values += ",";
            }
            values = values.substring(0, values.length() - 1);
            addSql.append(values + ") VALUES(" + sql + ");");

            logger.info(addSql.toString());
            execute = statement.executeUpdate(addSql.toString());
        }
        if (execute > 0)
            result = "增加成功!";
        else
            result = "增加失败!";
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("SQL语法错误!");
    }
    return result;
}

5.  更新操作

public static String updateTable(String table, String sql) {
    String result = "";
    int execute = 0;
    try {
        if (whetherExistsTable(table))
            execute = statement.executeUpdate(sql);
        if (execute > 0)
            result = "修改成功!";
        else
            result = "修改失败!";
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("SQL语法错误!");
    }
    return result;
}

6.  删除操作

public static String deleteTable(String table, String sql) {
    String result = "";
    int execute = 0;
    try {
        if (whetherExistsTable(table))
            execute = statement.executeUpdate(sql);
        if (execute > 0)
            result = "删除成功!";
        else
            result = "删除失败!";
    } catch (SQLException e) {
        e.printStackTrace();
        logger.error("SQL语法错误!");
    }
    return result;
}

7.  测试验证

public static void main(String[] args) {
    // 增加操作
    String addResult = addTable("user", "5,'张三','男'");
    logger.info(addResult);
    List<Map<String, Object>> addList = selectTable("user", "SELECT * FROM user where id=5;");
    logger.info(addList);
    
    // 更新操作
    String updateResult = updateTable("user", "UPDATE user SET name='赵六' WHERE id=5");
    logger.info(updateResult);
    List<Map<String, Object>> updateList = selectTable("user", "SELECT * FROM user where id=5;");
    logger.info(updateList);
    
    // 删除操作
    String deleteResult = deleteTable("user", "DELETE FROM user WHERE id=5;");
    logger.info(deleteResult);
    
    // 查询测试
    List<Map<String, Object>> list = selectTable("user", "SELECT * FROM user;");
    logger.info(list);
    
    release();
}

猜你喜欢

转载自blog.csdn.net/volitationLong/article/details/82776940
今日推荐