1 Import pandas as PD 2 import psycopg2 3 from IO import stringio 4 import pymysql 5 conf={"Mysql_form": {6 ' Host ': ' localhost ', 7 ' Port ': 3306, 8 ' db ': ' Pricefluctuation ', 9 ' user ': ' Root ', ' passwd ': ' huzu_mysql_qazwsx12# ', One ' charset ': ' UTF8 ', '},13 ' Mysql_ Test ": {' host ': ' 192.168.2.251 ', ' Port ': ' 3306,16 ' db ': ' Pricefluctuation ', ' user ' : ' Hewen ', ' passwd ': ' Meiyoumima ', ' charset ': ' UTF8 ',},21 ' Postgres ': {22 ' Host ': ' 120.79.135.9 ', ' Port ': ' 5432 ', ' user ': ' postgres ', ' Password ': ' 33068080 ', 26 },28}29 def sql_to_df (): Con=pymysql.connect (**conf["Mysql_form"]) sql= "Select Category_i D,name,gameid,img_url from category where category_id in (11665,9653,6504) "+ try:33 with Con.cursor () as Cur : cur.execUte (SQL) Datas=cur.fetchall () finally:37 con.close () df=pd. DataFrame (List (datas)) "Df40"-Df_to_pg (df=none,db= "Spider", table= ' price_730 '): #这里生成的StringIO类似于fi Le files, which can be read, can be write, different is file on hard disk, while Stringio is in memory file Output=stringio () #也可以直接将字符串转换成内存文件, #将数据保存到 ' file ' 46 If not df:47 df=sql_to_df () df.to_csv (output,sep= ' t ', Index=false,header=false) #使文件定位到第一个字符50 Output.seek (0) Wuyi try:52 conn=psycopg2.connect (database=db,**conf["Postgres"]) Cur=conn.cursor () 54 Cur.copy_from (output,table,null= ") conn.commit () result=cur.rowcount57 finally:58 Cur.close () Conn.close () return result61 if __name__== ' __main__ ': df=pd.read_csv (' E:/730_pric E.csv ') print (DF_TO_PG (table= "category")) 65
MySQL to PostgreSQL