# huaweicloud-gaussdbformysql-database-java **Repository Path**: HuaweiCloudDeveloper/huaweicloud-gaussdbformysql-database-java ## Basic Information - **Project Name**: huaweicloud-gaussdbformysql-database-java - **Description**: 增加示例文件。本示例展示如何通过java版本的SDK方式授权数据库用户。 - **Primary Language**: Unknown - **License**: Not specified - **Default Branch**: master-dev - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-09-19 - **Last Updated**: 2023-11-30 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 1. 介绍 GaussDB(for MySQL)是华为自研的最新一代企业级高扩展海量存储分布式数据库,完全兼容MySQL。基于华为最新一代DFV存储,采用计算存储分离架构,128TB的海量存储,无需分库分表,数据0丢失,既拥有商业数据库的高可用和性能,又具备开源低成本效益。本示例展示如何通过java版本的SDK方式授予数据库用户数据库权限。 ## 2.流程图 ![授予数据库用户数据库权限的流程图](assets/database.png) ## 3. 前置条件 1.已 [注册](https://reg.huaweicloud.com/registerui/cn/register.html?locale=zh-cn#/register) 华为云,并完成 [实名认证](https://account.huaweicloud.com/usercenter/?region=cn-north-4#/accountindex/realNameAuth) 。 2.获取华为云开发工具包(SDK),您也可以查看安装JAVA SDK。 3.已获取华为云账号对应的Access Key(AK)和Secret Access Key(SK)。请在华为云控制台“我的凭证 > 访问密钥”页面上创建和查看您的AK/SK。具体请参见 [访问密钥](https://support.huaweicloud.com/usermanual-ca/zh-cn_topic_0046606340.html) 。 4.已具备开发环境 ,支持Java JDK 1.8及其以上版本。 ## 4.SDK获取和安装 您可以通过Maven方式获取和安装SDK,首先需要在您的操作系统中下载并安装Maven ,安装完成后您只需要在Java项目的pom.xml文件中加入相应的依赖项即可。 具体的SDK版本号请参见 [SDK开发中心](https://sdkcenter.developer.huaweicloud.com?language=java) 。 ```xml com.huaweicloud.sdk huaweicloud-sdk-gaussdb 3.1.1 ``` ## 5.关键代码片段 以下代码展示如何使用SDK授予数据库用户数据库权限: ```java public class DatabaseDemo { private static final Logger logger = LoggerFactory.getLogger(DatabaseDemo.class.getName()); public static void main(String[] args) { // 认证用的ak和sk直接写到代码中有很大的安全风险,建议在配置文件或者环境变量中密文存放,使用时解密,确保安全; // 本示例以ak和sk保存在环境变量中来实现身份验证为例,运行本示例前请先在本地环境中设置环境变量HUAWEICLOUD_SDK_AK和HUAWEICLOUD_SDK_SK。 String ak = System.getenv("HUAWEICLOUD_SDK_AK"); String sk = System.getenv("HUAWEICLOUD_SDK_SK"); String instanceId = ""; String regionId = ""; ICredential auth = new BasicCredentials() .withAk(ak) .withSk(sk); GaussDBClient client = GaussDBClient.newBuilder() .withCredential(auth) .withRegion(GaussDBRegion.valueOf(regionId)) .build(); // 查询数据库列表 listDatabases(client, instanceId); // 创建数据库的名称和字符集 String dbName = ""; String dbCharacterSet = ""; // 创建数据库 createDatabase(client, instanceId, dbName, dbCharacterSet); // 查看用户列表 ListGaussMySqlDatabaseUserResponse listGaussMySqlDatabaseUserResponse = listDatabaseUsers(client, instanceId); if (listGaussMySqlDatabaseUserResponse != null) { // 查询数据库用户的结果取第一个数据库用户进行授权 String userName = listGaussMySqlDatabaseUserResponse.getUsers().get(0).getName(); String host = listGaussMySqlDatabaseUserResponse.getUsers().get(0).getHost(); // 授权数据库用户,只读选项取值为true或者false,这里以false为例 boolean readonly = false; addDatabasePermission(client, instanceId, userName, host, dbName, readonly); } } private static void listDatabases(GaussDBClient client, String instanceId) { ListGaussMySqlDatabaseRequest request = new ListGaussMySqlDatabaseRequest(); request.withInstanceId(instanceId); try { ListGaussMySqlDatabaseResponse response = client.listGaussMySqlDatabase(request); logger.info(response.toString()); } catch (ConnectionException e) { logger.error("ConnectionException", e); } catch (RequestTimeoutException e) { logger.error("RequestTimeoutException ", e); } catch (ServiceResponseException e) { logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg()); } } private static void createDatabase(GaussDBClient client, String instanceId, String dbName, String dbCharacterSet) { CreateGaussMySqlDatabaseRequest request = new CreateGaussMySqlDatabaseRequest(); CreateGaussMySqlDatabaseRequestBody body = new CreateGaussMySqlDatabaseRequestBody(); body.withDatabases(Collections.singletonList(new CreateGaussMySqlDatabase() .withName(dbName) .withCharacterSet(dbCharacterSet))); request.withInstanceId(instanceId) .withBody(body); try { CreateGaussMySqlDatabaseResponse response = client.createGaussMySqlDatabase(request); logger.info(response.toString()); } catch (ConnectionException e) { logger.error("ConnectionException", e); } catch (RequestTimeoutException e) { logger.error("RequestTimeoutException ", e); } catch (ServiceResponseException e) { logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg()); } } private static ListGaussMySqlDatabaseUserResponse listDatabaseUsers(GaussDBClient client, String instanceId) { ListGaussMySqlDatabaseUserRequest request = new ListGaussMySqlDatabaseUserRequest(); request.withInstanceId(instanceId); try { ListGaussMySqlDatabaseUserResponse response = client.listGaussMySqlDatabaseUser(request); logger.info(response.toString()); return response; } catch (ConnectionException e) { logger.error("ConnectionException", e); } catch (RequestTimeoutException e) { logger.error("RequestTimeoutException ", e); } catch (ServiceResponseException e) { logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg()); } return null; } private static void addDatabasePermission(GaussDBClient client, String instanceId, String userName, String host, String dbName, boolean readonly) { AddDatabasePermissionRequest request = new AddDatabasePermissionRequest(); request.withInstanceId(instanceId); GrantDatabasePermissionRequestBody body = new GrantDatabasePermissionRequestBody(); List databases = new ArrayList<>(); databases.add(new DatabasePermission() .withName(dbName) .withReadonly(false)); GrantDatabasePermission grantDatabasePermission = new GrantDatabasePermission() .withName(userName) .withHost(host) .withDatabases(databases); List grantDatabasePermissonList = new ArrayList<>(); grantDatabasePermissonList.add(grantDatabasePermission); body.withUsers(grantDatabasePermissonList); request.withBody(body); try { AddDatabasePermissionResponse response = client.addDatabasePermission(request); logger.info(response.toString()); } catch (ConnectionException e) { logger.error("ConnectionException", e); } catch (RequestTimeoutException e) { logger.error("RequestTimeoutException ", e); } catch (ServiceResponseException e) { logger.error("httpStatusCode: {}, errorCode: {}, errorMsg: {}", e.getHttpStatusCode(), e.getErrorCode(), e.getErrorMsg()); } } } ``` ## 6.返回结果示例 - 查询数据库列表(ShowGaussMySqlBackupPolicy)接口的返回值: ``` class ListGaussMySqlDatabaseResponse { databases: [class ListGaussMysqlDatabaseInfo { name: database_final charset: gbk users: null }] totalCount: 1 } ``` - 创建数据库(CreateGaussMySqlDatabase)接口的返回值: ``` class CreateGaussMySqlDatabaseResponse { jobId: f1a44bd9-b0e6-45b6-9aab-2ddbf7241a82 } ``` - 查询数据库用户列表(ListGaussMySqlDatabaseUser)接口的返回值: ``` class ListGaussMySqlDatabaseUserResponse { users: [class ListGaussMySqlDatabaseUser { name: user_test_1 host: 127.0.0.1 databases: [] }, class ListGaussMySqlDatabaseUser { name: user_test_2 host: % databases: [] }] totalCount: 2 } ``` - 授予数据库用户数据库权限 (AddDatabasePermission)接口的返回值: ``` class AddDatabasePermissionResponse { jobId: 42cd2303-1d53-4ace-810c-126e89084a9e } ``` ## 7.参考链接 请见 [查询数据库列表API](https://support.huaweicloud.com/api-gaussdbformysql/ListGaussMySqlDatabase.html) 您可以在 [API Explorer](https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=GaussDB&api=ListGaussMySqlDatabase) 中直接运行调试该接口。 请见 [创建数据库API](https://support.huaweicloud.com/api-gaussdbformysql/CreateGaussMySqlDatabase.html) 您可以在 [API Explorer](https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=GaussDB&api=CreateGaussMySqlDatabase) 中直接运行调试该接口。 请见 [查询数据库用户API](https://support.huaweicloud.com/api-gaussdbformysql/ListGaussMySqlDatabaseUser.html) 您可以在 [API Explorer](https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=GaussDB&api=ListGaussMySqlDatabaseUser) 中直接运行调试该接口。 请见 [授予数据库用户数据库权限API](https://support.huaweicloud.com/api-gaussdbformysql/AddDatabasePermission.html) 您可以在 [API Explorer](https://apiexplorer.developer.huaweicloud.com/apiexplorer/doc?product=GaussDB&api=AddDatabasePermission) 中直接运行调试该接口。 ## 修订记录 | 发布日期 | 文档版本 | 修订说明 | |:----------:| :------: | :----------: | | 2022-09-19 | 1.0 | 文档首次发布 |