Python同步数据库的数据到Neo4J

时间:2022-12-12 18:03:10

写了主要是步骤,如果疑问,请咨询QQ:5988628

Python版本采用2.7.X,默认的2.6.X后期会有问题,建议,一开始就升级Python。然后再安装pip。

 

访问数据库

sqlalchemy + pyodbc,要是从linux访问windows 上的MS Sql Server,还需要安装freetds

 

访问Neo4J的驱动采用 neo4j-rest-client

https://neo4j-rest-client.readthedocs.org/en/latest/info.html

 

以下是示例代码:

#StatService.py
import urllib
import time
import sqlalchemy
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
from sqlalchemy import Column, Integer, String, Text, ForeignKey, Numeric, Unicode
from datetime import datetime

from neo4jrestclient.client import GraphDatabase

class StatService:

def __init(self):pass

def Run(self):
print 'Hello, World!'

quoted = urllib.quote_plus('DRIVER={FreeTDS};Server=xxx.meiyuetao.idc;Database=xxx;UID=xxx;PWD=xxx;TDS_Version=7.0;Port=1433;')
engine = sqlalchemy.create_engine('mssql+pyodbc:///?odbc_connect={0}'.format(quoted))

#读取数据库示例
connection = engine.connect()
result = connection.execute("select * from t_sys_config_parameter where code = 'RELATION_SYNC'")
for row in result:
print "value:", row['value']
connection.close()

#处理逻辑,数据映射等

#插入数据到Neo4J示例
gdb = GraphDatabase("http://localhost:7474/db/data/")
n = gdb.nodes.create(Name="Jason")
root = gdb.node[0]
root.relationships.create("Referral", n)


if __name__ == '__main__':
StatService().Run()

#End