使用 Java 备份 MySQL 数据库
Taking Backup of MySQL database using Java
我需要使用 Java 备份 MySQL 数据库。即,如果我 运行 class 文件,它应该进行备份。即在特定位置创建转储文件。
这是我为您提供的示例解决方案。
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM.........;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
//TODO Write on your file
}
//TODO
//**Process your file **/
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
用户下面的代码使用 Java
进行 MySQL 转储备份
public static void main(String[] args) {
try {
File dir = new File("/root/");
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("mysqldump database_name >/path-for-backpfile/database.sql", null, dir);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e1) {
}
}
我需要使用 Java 备份 MySQL 数据库。即,如果我 运行 class 文件,它应该进行备份。即在特定位置创建转储文件。
这是我为您提供的示例解决方案。
public static void main(String[] args) {
Connection con = null;
Statement st = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost/t";
String user = "";
String password = "";
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, password);
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM.........;");
if (rs.next()) {//get first result
System.out.println(rs.getString(1));//coloumn 1
//TODO Write on your file
}
//TODO
//**Process your file **/
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.SEVERE, ex.getMessage(), ex);
} finally {
try {
if (rs != null) {
rs.close();
}
if (st != null) {
st.close();
}
if (con != null) {
con.close();
}
} catch (SQLException ex) {
Logger lgr = Logger.getLogger(Version.class.getName());
lgr.log(Level.WARNING, ex.getMessage(), ex);
}
}
}
用户下面的代码使用 Java
进行 MySQL 转储备份public static void main(String[] args) {
try {
File dir = new File("/root/");
Runtime runtime = Runtime.getRuntime();
Process p = runtime.exec("mysqldump database_name >/path-for-backpfile/database.sql", null, dir);
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
String line = reader.readLine();
while (line != null) {
System.out.println(line);
line = reader.readLine();
}
} catch (IOException e1) {
}
}