import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.util.Date;
public class Test {
private static final String USERNAME = "root";
private static final String PASSWORD = "root";
private static final String SLAVE_URL = "jdbc:mysql://192.168.1.104:3306/test_db?autoReconnect=true&useUnicode=true&characterEncoding=utf-8";
private static final String MASTER_URL = "jdbc:mysql://192.168.1.102:3306/test_db?autoReconnect=true&useUnicode=true&characterEncoding=utf-8";
public static void main(String[] args) throws SQLException {
select();
insert("张三", "男");
select();
}
public static void select() throws SQLException {
try (Connection conn = getSlaveConnection()) {
String sql = "SELECT * FROM USER";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
try (ResultSet rs = stmt.executeQuery()) {
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
String sex = rs.getString("sex");
Date createTime = rs.getTimestamp("create_time");
LocalDateTime datetime = createTime.toInstant().atZone(ZoneId.systemDefault())
.toLocalDateTime();
System.out.println(id + "\t" + name + "\t" + sex + "\t" + datetime);
}
System.out.println("--- 查询结束 ---");
}
}
}
}
public static void insert(String name, String sex) throws SQLException {
try (Connection conn = getMasterConnection()) {
String sql = "INSERT INTO USER(id, name, sex, create_time) VALUES(null, ?, ?, now())";
try (PreparedStatement stmt = conn.prepareStatement(sql)) {
stmt.setString(1, name);
stmt.setString(2, sex);
stmt.executeUpdate();
}
}
}
public static Connection getSlaveConnection() throws SQLException {
return DriverManager.getConnection(SLAVE_URL, USERNAME, PASSWORD);
}
public static Connection getMasterConnection() throws SQLException {
return DriverManager.getConnection(MASTER_URL, USERNAME, PASSWORD);
}
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
}