python操作数据库

Posted miyatest

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python操作数据库相关的知识,希望对你有一定的参考价值。

import pymysql
conn = pymysql.connect(host=118.24.3.40,user=jxz,
                password=123456,port=3306,
                db=jxz,charset=utf8,autocommit=True)
cur = conn.cursor(pymysql.cursors.DictCursor) #建立游标
# sql=‘select * from app_myuser;‘
# sql=‘insert into app_myuser (username,passwd,is_admin) values ("nhy123","456789",1);‘
# cur.execute(sql)#只是执行sql,并不会返回数据
# conn.commit()
name =nhy123
# sql2 = ‘select * from app_myuser where username="%s";‘%name
sql3 =  select * from app_myuser limit 5;
cur.execute(sql3)
# print(cur.fetchall()) #获取到所有返回的数据
print(cur.fetchone()) #只取一条数据
cur.close()
conn.close()

#upadte insert delete

def my_db(host,user,passwd,db,sql,port=3306,charset=utf8,autocommit=True):
    conn = pymysql.connect(host=host,user=user,password=passwd,
                    db=db,port=port,charset=charset,autocommit=autocommit)
    cur = conn.cursor()
    cur.execute(sql)
    res = cur.fetchall()
    cur.close()
    conn.close()  #返回一个字典
    return res

#fetchall()
#((1,nhy,123456,1),(2,nhy123,12345,0),(3,nh456,12356,1))
#(1,nhy,123456,1)
#fetchone()


#fetchall()
#[
# {"id":1,"username":"nhy","passwd":"123456","is_admin":1},
# {"id":2,"username":"nhy123","passwd":"123456","is_admin":1},
# {"id":3,"username":"nhy456","passwd":"123456","is_admin":1},
#  ]

#  {"id":3,"username":"nhy456","passwd":"123456","is_admin":1}
#fetchone()

 

以上是关于python操作数据库的主要内容,如果未能解决你的问题,请参考以下文章

[未解决问题记录]python asyncio+aiohttp出现Exception ignored:RuntimeError('Event loop is closed')(代码片段

常用python日期日志获取内容循环的代码片段

python 有用的Python代码片段

Python 向 Postman 请求代码片段

Python - 循环加速 - 大型数据集

VSCode自定义代码片段——git命令操作一个完整流程