原創!
前提:目前MySql數據庫中有兩個數據庫,名稱分別為:db01和db02。db01中的人員表叫t_user_info;db02中的人員表叫t_user。需求:將表t_user_info(id,name,type,content,createtime)的數據導入到表t_use( userid,username,usertype, usercontent,user createtime)中。
第一步:運用JDBC建立數據源
/**
* JDBC連接數據庫(db01) bgy
* @return Connection
*/
public static Connection getConnection01() throws SQLException,java.lang.ClassNotFoundException
{
//第一步:加載MySQL的JDBC的驅動
Class.forName("com.mysql.jdbc.Driver");
//取得連接的url,能訪問MySQL數據庫的用戶名,密碼;db01:數據庫名
String url = "jdbc:mysql://192.168.88.1:3306/db01";
String username = "bgy01";
String password = "123456";
//第二步:創建與MySQL數據庫的連接類的實例
Connection con01 = (Connection) DriverManager.getConnection(url, username, password);
return con01;
}
/**
* JDBC連接數據庫(db02) bgy
* @return Connection
*/
public static Connection getConnection02() throws SQLException,java.lang.ClassNotFoundException
{
//第一步:加載MySQL的JDBC的驅動
Class.forName("com.mysql.jdbc.Driver");
//取得連接的url,能訪問MySQL數據庫的用戶名,密碼;db02:數據庫名
String url = "jdbc:mysql://192.168.88.2:3306/db02";
String username = "bgy02";
String password = "123456";
//第二步:創建與MySQL數據庫的連接類的實例
Connection con02 = (Connection) DriverManager.getConnection(url, username, password);
return con02;
}
第二步:同步數據實現詳細(方法dSynchronous())
/**
* 同步數據 bgy
* @return String
* @throws ClassNotFoundException
* @throws SQLException
*/
public String dSynchronous() throws SQLException, ClassNotFoundException
{
//前台傳來值
String param = request.getParameter("param");
try
{
//設置“db01”數據源
Connection con01 = getConnection01();
Statement sql_statement01 = (Statement) con01.createStatement();
//設置“db02”數據源
Connection con02 = getConnection02();
Statement sql_statement02 = (Statement) con02.createStatement();
//人員信息1
if("1".equals(param))
{
//定位至db01
sql_statement01.executeUpdate("use db01");
//定位至db02
sql_statement02.executeUpdate("use db02");
//刪除“db02”用戶表t_user的數據
String query1 = "TRUNCATE TABLE t_user;"; //TRUNCATE比DELETE效率高太多
sql_statement02.executeUpdate(query1);
String query2 = "ALTER TABLE t_user AUTO_INCREMENT=1;"; //自增序列設為1
sql_statement02.executeUpdate(query2);
//向“db02”用戶表t_user插入數據
int tag = sql_statement02.executeUpdate("INSERT INTO db02.t_user (id, name,type,content,createtime) SELECT userid, username, usertype, usercontent, usercreatetime FROM db01.t_user_info");
String jsondata = null;
if(tag > 0)
{
jsondata = "{'flag':'ok'}";
}
else
{
jsondata = "{'flag':'error'}";
}
}
//“其余”
if("2".equals(param))
{
//業務邏輯代碼
}
//“其余”
else
{
//業務邏輯代碼
}
//關閉數據源
sql_statement01.close();
conWly.close();
sql_statement02.close();
conYxl.close();
}
catch(java.lang.ClassNotFoundException e)
{
//加載JDBC錯誤,所要用的驅動沒有找到
System.err.print("ClassNotFoundException");
//其他錯誤
System.err.println(e.getMessage());
}
catch(SQLException ex)
{
//顯示數據庫連接錯誤或查詢錯誤
System.err.println("SQLException: " + ex.getMessage());
}
return SUCCESS;
}