-
Notifications
You must be signed in to change notification settings - Fork 0
/
synctable.py
77 lines (64 loc) · 2.22 KB
/
synctable.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
#coding=utf-8
import pyodbc
import sys
class SyncTable(object):
l=[]
@staticmethod
def info():
# db = raw_input("please input sync database name:")
# table = raw_input("please input sync table name:")
print("--------------此程序是把20上的表同步到172中----------------".decode('utf-8').encode(sys.getfilesystemencoding()))
db = raw_input("请输入要同步的数据库:".decode('utf-8').encode(sys.getfilesystemencoding()))
table = raw_input("请输入要同步的表:".decode('utf-8').encode(sys.getfilesystemencoding()))
SyncTable.l.append(db)
SyncTable.l.append(table)
def __init__(self,db,table):
try:
self.conn = pyodbc.connect('DRIVER={SQL Server Native Client 10.0};SERVER=10.7.1.172;DATABASE=%s;UID=sa;PWD=cargosa'%db)
self.cursor = self.conn.cursor()
self.db = db
self.table = table
# self.dsql = "delete from %s"%table
# self.sql = "select c.name from sys.columns c,sys.tables t where t.name='%s' and t.object_id=c.object_id and c.is_identity<>1"%table
# self.isql = "insert into %s(%s) select %s from [10.7.1.172].%s.dbo.%s"%(table,c,c,db,
except Exception, e:
self.close()
print("同步出错了".decode('utf-8').encode(sys.getfilesystemencoding()))
raise(e)
def run(self,sql):
self.cursor.execute(sql)
def close(self):
self.cursor.close()
self.conn.close()
def commit(self):
self.cursor.commit()
def rollback(self):
self.cursor.rollback()
def start(self):
col = ''
csql = "select c.name from sys.columns c,sys.tables t where t.name='%s' and t.object_id=c.object_id and c.is_identity<>1"%self.table
self.run(csql)
row = self.cursor.fetchall()
for i in row:
col+=i[0]+','
col=col[:-1]
isql = "insert into %s(%s) select %s from [10.7.1.20].%s.dbo.%s"%(self.table,col,col,self.db,self.table)
dsql = "delete from %s"%self.table
self.run(dsql)
self.run(isql)
def sync(self):
try:
self.start()
self.commit()
print("sync successful")
except Exception, e:
self.rollback()
print("sync failure")
finally:
self.close()
def main():
SyncTable.info()
sync = SyncTable(SyncTable.l[0],SyncTable.l[1])
sync.sync()
if __name__ == '__main__':
main()