用python或R往数据库上传数据

≯℡__Kan透↙ 提交于 2020-11-07 09:43:39

如何使用python或R往数据库上传数据

多数情况下,我们是用python或R从数据库里面提取数据,但有的时候为了工作方便,我们会需要建一个临时表。

一、用python在数据库建立临时表并上传数据

本文以postgresql为例 代码如下(示例):
import string
import psycopg2
import random
conn = psycopg2.connect(database="dbname",user="user",password="your_password", host="your_host",port="your_port")
cur = conn.cursor()
cur.execute('''drop table if exists table_test_kk''')
conn.commit()
cur.execute('''create table table_test_kk(uid integer,life_group integer,money_group integer)''')
conn.commit()

# 上传数据  uid是我想上传上去的一个dataframe,他有3for i in range(uid.shape[0]):
    cur.execute(f"""insert into table_test_kk (uid,life_group,money_group) values {uid.iloc[i,0]},{uid.iloc[i,1]},{uid.iloc[i,2]})""")
conn.commit()
conn.close()

二、用R语言在数据库建立临时表并上传数据

代码如下:

# 将uid上传到数据库
dbSendQuery(your_db, "drop table if exists table_test_kk ")
dbSendQuery(your_db, "create table table_test_kk(uid integer,life_group integer,money_group integer) ")
newpaste <- function(x)
{
   
   
    paste('(', paste(x, collapse=','), ')', sep="")
}
str <- paste('rs <- dbSendQuery(your_db, ',
                              '"insert into table_test_kk (uid,life_group,money_group) values ' ,
                                paste(apply(pay.ability[,c('uid','life_group','money_life')],1,newpaste), collapse='),('), ')', sep=""), '")' )
eval(parse(text=str))
dbSendQuery(your_db, "create index table_test_kk_idx1 on table_test_kk using btree(uid)")
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!