[java代码实现数据库同步]java实现数据库同步

这里实现方式事先说明下,采用json+文本流方式,即读取数据库信息至文本流中,格式采用json,之后读取文本中json数据至数据库中,实现度还不完全,不过也提供了一种解决方案,目前可支持同类型数据库表同步,使用后可根据个人需要进行不同表数据库同步进行修改,仅贡献个人代码给各位大神。

再次说明下由于各个数据库中关于数字的类型可能有所不同,所以这里提供了一个db2拓展实现作为demo,其他数据库可以效仿。

publicabstractclassDBTools{

protectedConnectionconn=null;

protectedStatementstmt=null;

protectedResultSetrs=null;

protectedStringusername;//数据库用户名

protectedStringpassword;//数据库密码

protectedStringdbname;//数据库名称

//数据库中的数字域

protectedListnumList=newArrayList();

protectedbooleanconnectDB(Stringdbname,String

user,Stringpassword)

throws

Exception{

//加载驱动程序以连接数据库

try{

Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

conn=DriverManager.getConnection("jdbc:odbc:"+dbname,user,

password);

//url="jdbc:db2:njtcdata";

}

//捕获加载驱动程序异常

catch(ClassNotFoundException

cnfex){

System.err.println("装载JDBC驱动程序失败。");

cnfex.printStackTrace();

return

false;

}

//捕获连接数据库异常

catch(SQLExceptionsqlex)

{

System.err.println("无法连接数据库");

sqlex.printStackTrace();

//

System.exit(1);//terminateprogram

return

false;

}

returntrue;

}

protectedintexecuteSQL(Stringsql)throws

SQLException{

System.out.println(sql);

return

stmt.executeUpdate(sql);

}

protectedResultSetquery(Stringsql)throws

Exception{

//先打印出SQL

System.out.println(sql);

try{

Statement

stmt=conn.createStatement(

ResultSet.TYPE_SCROLL_SENSITIVE,

ResultSet.CONCUR_READ_ONLY);

rs=stmt.executeQuery(sql);

}catch(Exceptione){

e.printStackTrace();

thrownew

Exception("执行查询语句错误!",e);

}

returnrs;

}

protectedvoidcolseConnect()throwsException

{

if(stmt!=null)

stmt.close();

if(conn!=null)

conn.close();

if(rs!=null)

rs.close();

//conn.close();

}

protectedStringcreateFilePath(){

Datedt=newDate();

SimpleDateFormatsf=new

SimpleDateFormat("yyyy-MM-dd-hh-mm-sss");

Stringfilename=System.getProperty("user.dir")+"\src\"

+

sf.format(dt)+".txt";

returnfilename;

}

protectedStringgeneralInsertSQL(Stringtable,

JSONObjectjobject,

JSONArray

columns)throwsJSONException{

StringBuffersb=new

StringBuffer();

sb.append("insertinto"+

table+"(");

for(inti=0;i

JSONObject

jcolumn=columns.getJSONObject(i);

Stringcolumn=jcolumn.getString("COLNAME");

sb.append(column);

if(i!=columns.length()-1){

sb.append(",");

}

}

sb.append(")values(");

for(inti=0;i

JSONObject

jcolumn=columns.getJSONObject(i);

Stringcolumn=jcolumn.getString("COLNAME");

String

typecolumn=jcolumn.getString("TYPENAME");

String

datacolumn=jobject.getString(column).equals("null")?null

:jobject.getString(column);

if(datacolumn==null)

{

sb.append("null");

}elseif

(numList.contains(typecolumn)){

//

是数字域

sb.append(datacolumn);

}else

{

//

文本域或者日期域

sb.append("'"

+datacolumn+"'");

}

if(i!=columns.length()-1){

sb.append(",");

}

}

sb.append(")");

returnsb.toString();

}

protectedStringgeneralTextSQL(JSONArray

columns,Stringtablename,

String

condition)throwsJSONException{

StringBuffersb=new

StringBuffer();

sb.append("select");

for(inti=0;i

JSONObject

jcolumn=(JSONObject)columns.get(i);

Stringcolumn=jcolumn.getString("COLNAME");

//String

strColumn="casewhen"+column

//+

"isnullthen''elsechar("+column+")end

as"

//+

column;

String

strColumn=column;

sb.append(strColumn);

if(i!=columns.length()-1){

sb.append("

,");

}

}

sb.append("

from"+tablename);

if(!condition.equals(""))

{

//

添加控制条线

sb.append("

where"+condition);

}

returnsb.toString();

}

publicStringreadToFile(Stringtable,String

condition)throwsException{

Stringpath=createFilePath();

Filefile=newFile(path);

JSONArraycolumns=queryTableColumns(table);

if(columns==null){

//

读取表失败

System.out.println("读取表失败");

return

null;

}

Stringsql=generalTextSQL(columns,table,condition);

ResultSetrs=query(sql);

FileOutputStreamfout=new

FileOutputStream(file);

System.out.println("开始读取表到文件中...");

intindex=0;

fout.write("[".getBytes());

while(rs.next()){

StringBuffer

sb=newStringBuffer();

sb.append("{");

for(inti=0;i

JSONObject

jcolumn=(JSONObject)columns.get(i);

String

column=jcolumn.getString("COLNAME");

String

columndate=rs.getString(column);

String

addDateStr="""+column+"":""+columndate+""";

sb.append(addDateStr);

if

(i!=columns.length()-1){

sb.append(",");

}

}

if(rs.isLast())

{

sb.append("}");

}else{

sb.append("},");

}

fout.write(sb.toString().getBytes());

index++;

}

fout.write("]".getBytes());

System.out.println("读取完毕!");

System.out.println("读取总数据量为:"+index+"条!");

System.out.println("文件路径为!");

System.out.println(path);

returnpath;

}

publicbooleanreadToDatabase(Stringtable,

StringfilePath)throwsException

{

JSONArraycolumns=queryTableColumns(table);

if(columns==null){

//

读取表失败

return

false;

}

//先打印出SQL

try{

conn.setAutoCommit(false);

Statement

stmt=conn.createStatement();

System.out.println("开始读取文件...");

Filefile=newFile(filePath);

FileInputStream

filein=newFileInputStream(file);

byte[]in=newbyte[999];

bytetemp

;

intindex=0;

while((temp=(byte)filein.read())!=-1)

{

if(temp==123)

{

//{

index=0;

in[index++]=temp;

}else

if(temp==125)

{

//}

in[index++]=temp;

String

str=newString(in,"gbk");

JSONObject

jobject=newJSONObject(str);

String

insertSQL=generalInsertSQL(table,jobject,columns);

System.out.println(insertSQL);

stmt.executeUpdate(insertSQL);

//重新更新in内存

in=null;

in=newbyte[999];

}else

{

in[index++]=temp;

}

}

System.out.println("读取文件完毕");

System.out.println("开始插入数据库...");

conn.commit();

System.out.println("插入数据库完毕!");

}catch(Exceptione){

try{

conn.rollback();

}catch

(SQLExceptione2){

//

TODOAuto-generatedcatchblock

e2.printStackTrace();

}

e.printStackTrace();

try{

throw

newException("执行查询语句错误!",e);

}catch

(Exceptione1){

//

TODOAuto-generatedcatchblock

e1.printStackTrace();

}

}

returntrue;

}

publicabstractJSONArray

queryTableColumns(Stringtable)throwsException;

}publicclassTestTransDB2extendsDBTools{

publicTestTransDB2(Stringdbname,String

username,Stringpassword)

{

numList.add("INTEGER");

numList.add("DECIMAL");

this.dbname=dbname;

this.username=username;

this.password=password;

try{

connectDB(dbname,

username,password);

}catch(Exceptione){

//TODO

Auto-generatedcatchblock

e.printStackTrace();

}

}

publicJSONArrayqueryTableColumns(Stringtable)

throwsException{

//检验表名是否存在

Stringsql="Select

COLNAME,TYPENAMEfromSYSCAT.COLUMNSWHERETABNAME='"+table+"'

orderbyCOLNO";

//System.out.println(sql);

Statementstmt=conn.createStatement();

rs=stmt.executeQuery(sql);

JSONArrayresult=new

JSONArray();

while(rs.next())

{

JSONObject

jobject=newJSONObject();

String

COLNAME=rs.getString("COLNAME").toString();

String

TYPENAME=rs.getString("TYPENAME").toString();

jobject.put("COLNAME",

COLNAME);

jobject.put("TYPENAME",

TYPENAME);

result.put(jobject);

}

if(result.length()==0)

{

return

null;

}else

{

return

result;

}

}

}

猜你喜欢

转载自www.cnblogs.com/sqlserver-mysql/p/12724375.html
今日推荐