欧美一区二区三区,国内熟女精品熟女A片视频小说,日本av网,小鲜肉男男GAY做受XXX网站

java開發連接主從復制mysql

李中冰2年前13瀏覽0評論

Java開發連接主從復制MySQL,需要使用到MySQL提供的主從復制機制,主服務器用于寫操作,從服務器用于讀操作,可以提高數據庫的讀寫效率。以下是連接主從復制MySQL的步驟。

1. 創建主從服務器

CREATE SERVER server_master
FOREIGN DATA WRAPPER mysql
OPTIONS (USER 'user', HOST 'master_host_name',
PORT 'port_number', DATABASE 'db_name', PASSWORD 'password');
CREATE SERVER server_slave
FOREIGN DATA WRAPPER mysql
OPTIONS (USER 'user', HOST 'slave_host_name',
PORT 'port_number', DATABASE 'db_name', PASSWORD 'password');

2. 創建用戶映射

CREATE USER MAPPING FOR user
SERVER server_master
OPTIONS (USERNAME 'master_user', PASSWORD 'master_password');
CREATE USER MAPPING FOR user
SERVER server_slave
OPTIONS (USERNAME 'slave_user', PASSWORD 'slave_password');

3. 創建外部表

CREATE FOREIGN TABLE table_name (
column1 data_type,
column2 data_type,
column3 data_type)
SERVER server_master
OPTIONS (SCHEMA_NAME 'db_name', TABLE_NAME 'table_name');
CREATE FOREIGN TABLE table_name (
column1 data_type,
column2 data_type,
column3 data_type)
SERVER server_slave
OPTIONS (SCHEMA_NAME 'db_name', TABLE_NAME 'table_name');

4. 編寫Java代碼

String url = "jdbc:mysql://localhost:3306/db_name";
String user = "root";
String password = "123456";
String driver = "com.mysql.jdbc.Driver";
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
Connection masterConn = DriverManager.getConnection(url, user, password);
Connection slaveConn = DriverManager.getConnection(url, user, password);
Statement statement = masterConn.createStatement();
ResultSet resultSet = statement.executeQuery("SELECT * FROM table_name");
while (resultSet.next()) {
System.out.println(resultSet.getString("column1"));
}
statement = slaveConn.createStatement();
resultSet = statement.executeQuery("SELECT * FROM table_name");
while (resultSet.next()) {
System.out.println(resultSet.getString("column1"));
}

以上就是Java開發連接主從復制MySQL的步驟,需要注意的是在創建外部表時,需要指定SCHEMA_NAME和TABLE_NAME。