如何使用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,他有3列
for 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)")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/205119.html
標籤:其他
