码迷,mamicode.com
首页 > 数据库 > 详细

python操作数据库

时间:2018-12-15 18:48:34      阅读:490      评论:0      收藏:0      [点我收藏+]

标签:cursor   imp   hal   charset   use   fetch   into   mys   int   

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操作数据库

标签:cursor   imp   hal   charset   use   fetch   into   mys   int   

原文地址:https://www.cnblogs.com/miyatest/p/10124175.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!