公司因为要更换服务器域名,导致存储在数据库的图片Url域名需要替换为新服务器的域名,
使用jdbc 连接mysql 查询每张表的值是否包含需要替换的url
1.连接mysql数据库
public void DBinit() {
//MySQL配置时的用户名
//String user = "root";
//从配置文件获取数据库账号
String user=environment.getProperty("spring.datasource.username");
//MySQL配置时的密码
// String password = "123456";
String password=environment.getProperty("spring.datasource.password");
//String url = "jdbc:mysql://127.0.0.1:3306/bobo?useUnicode=true&characterEncoding=UTF-8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai";
String url=environment.getProperty("spring.datasource.url");
try {
Class.forName("com.mysql.cj.jdbc.Driver");
//声明Connection对象
conn = DriverManager.getConnection(url, user, password);
} catch (Exception e) {
System.out.println(e);
}
}
public static void DBclose() {
try {
conn.close();
} catch (SQLException e) {
//TODO Auto-generated catch block
System.out.println("数据关闭异常");
e.printStackTrace();
}
}
2.查询表数据,并替换新URL
DBinit();
try {
//获取数据库的元数据
DatabaseMetaData dbMetaData = conn.getMetaData();
//从元数据中获取到所有的表名
ResultSet rs = dbMetaData.getTables("bobo", "null", null, new String[]{"TABLE"});
//存放所有表名
List<String> tableNames = new ArrayList<>();
while (rs.next()) {
tableNames.add(rs.getString("TABLE_NAME"));
}
//查询每个表的字段
for (String record : tableNames) {
String sql = "select * from " + record;
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rsTable = ps.executeQuery();
//结果集元数据
ResultSetMetaData meta = rsTable.getMetaData();
//表列数量
int columeCount = meta.getColumnCount();
for (int i = 1; i <= columeCount; i++) {
if (meta.getColumnTypeName(i).equals("VARCHAR") || meta.getColumnTypeName(i).equals("LONGTEXT") || meta.getColumnTypeName(i).equals("TEXT")) {
String columnName = meta.getColumnName(i);
//移动指针到开始位置
rsTable.beforeFirst();
while (rsTable.next()) {
String name = rsTable.getString(columnName);
//判断值是否包含被替换Url
if (StringUtils.containsIgnoreCase(name, "https://oss.xxxxx.com")) {
//替换为更换的Url
String repName = name.replaceAll("https://oss.xxxxx.com", "https://oss.xxxxx.com");
//拼接修改语句
String updateSql = "update " + record + " set " + columnName + "=" + "'" + repName + "'" + " where " + columnName + "=" + "'" + name + "'";
PreparedStatement preparedStatement = conn.prepareStatement(updateSql);
preparedStatement.executeUpdate();
}
}
}
}
}
} catch (SQLException e) {
e.printStackTrace();
}
DBclose();
return success();
网友评论