python 连接数据库 增删查改

1.插入数据
2.更新数据
进阶:遍历表,插入,并更新数据

import time
import pymysql

conn= pymysql.connect(
        host='localhost',
        port = 3306,
        user='root',
        passwd='154524',
        db ='test',
        )
cur = conn.cursor()
#插入一条数据
cur.execute("insert into student values('5','8om','3 year 2 class','9')")
#修改查询条件的数据
cur.execute("update student set class='3 year 1 class' where name = 'Tom'")
cur.execute('select ssh from {}'.format("pro_test"))
#遍历表的数据,读取并更新
list = []          ## 空列表
for promsg in cur:
    ssh_url=promsg[0]
    print(ssh_url)
    upadtemsg="update pro_test set url='"+http_url+"' where ssh ='"+ssh_url+"'"
    list.append(upadtemsg)  

for item in list :
    cur.execute(item)

cur.close()
conn.commit()
conn.close()

参考文章:python连接数据库
通过mysqlclient操作MySQL数据库

封装入库方法

import pymysql

#sql是否需要获取返回值
GET_RES=1  
NO_RES=0 

###
# updatedb:更新数据库
# 执行sql实现增删查改
###
def updatedb(sql,flag):
    rs = ()
    conn= pymysql.connect(
            host='localhost',
            port=3306,
            user='root',
            passwd='154524',
            db='test',
            )
    cur = conn.cursor()
    try:
        cur.execute(sql)
        if flag == GET_RES:   #需要获取返回值
            rs = cur.fetchall()
    except Exception as e:
        print("执行失败", e)
    cur.close()
    conn.commit()
    conn.close()
    return rs 

#执行sql
sql="insert into "+TABLE+" (jobname,jobpath) values ('"+jobname+"','"+jobpath+"');" #任务信息入库sql
updatedb(sql,NO_RES) 
#需要获取sql执行返回值
sql="select * from "+TABLE+" where jobpath='"+jobpath+"'" #查询任务地址为xxx的所有任务 
joblist=updatedb(sql,GET_RES)
if len(joblist) != 0 :
    for joblisti in joblist :
        jobname=joblisti[1]  #获取到任务名

你可能感兴趣的:(#,python,python,big,data,mysql)