首页 > 编程 > Python > 正文

python mysql CRUD

2019-11-08 03:16:19
字体:
来源:转载
供稿:网友
#coding:utf-8import MySQLdbimport json#连接conn= MySQLdb.connect(        host='localhost',        port = 3306,        user='root',        passwd='',        db ='test'        )cur=conn.cursor()#单条插入cur.execute("insert into user (name ,age,sex) value ('%s',%s,%s)"%('a',1,1))#批量cur.executemany("insert into user (name ,age,sex) values (%s,%s,%s)",[("e", 1, 1), ("f", 1, 1), ("g", 1, 1)])#查询单条cur.execute("select * from user where id = %s and name = '%s'" % (1,'张三'))res_data=json.dumps(cur.fetchone(),ensure_ascii=False,encoding="utf8")PRint res_data#查询多条cur.execute("select * from user")res_data=json.dumps(cur.fetchmany(15),ensure_ascii=False,encoding="utf8")
print res_data#修改
cur.execute("update user set name='%s' where id= %s"%('王麻子',1))
#删除
cur.execute("delete from user where id=2")
conn.commit()
cur.close()
conn.close()
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表