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

Mysql在python中的使用:pymysql

时间:2020-06-30 14:27:33      阅读:71      评论:0      收藏:0      [点我收藏+]

标签:添加   key   man   error:   bsp   nec   完数   ctc   error   

import pymysql

1.登录mysql

conn = pymysql.connect(host= ‘127.0.0.1‘,user=‘root‘,password=‘123‘,database=‘homework‘)

2.获取游标

cur = conn.cursor()

# cur = conn.cursor(cursor=pymysql.cursors.DictCursor)#查询结果返回字典

3.查select

# cur.execute(‘select * from student‘)

# ret = cur.fetchone()#获取游标后第一条值

# print(ret)

# ret = cur.fetchmany(10)#返回元组,获取游标后多条

# print(ret)

# ret = cur.fetchall()#返回元组,获取游标后全部

# print(ret)

 

4.增,删,改

# try:

#     cur.execute(‘delete from student where sid = 17‘)

#     cur.execute(‘insert into student values(17,"男",3,"大壮")‘)

#     cur.execute(‘update student set gender="女" where sid = 17‘)

#     conn.commit()

# except Exception as e:

#     print("Error:",e)

#     conn.rollback()

# print(‘操作完成!‘) 

5.rowcount

这是一个只读属性,并返回执行execute()方法后影响的行数。

# cur.execute(‘select * from student‘)

# print(cur.rowcount)

# for i in range(cur.rowcount):

#     print(cur.fetchone())

 

 

6. 写入用户信息

# sql = ‘create table userinfo(id int unsigned primary key auto_increment,name char(12),password char(20)) ‘

# cur.execute(sql)

# sql = ‘insert into userinfo(name,password) values("hanshiqu","sss123")‘

# cur.execute(sql)

# conn.commit()

 

7.用户登录系统

# name = input("用户名:")

# pwd = input("密码:")

# l = ‘select * from userinfo where name = %s and password = %s‘

# cur.execute(l,(name,pwd))

# ret = cur.fetchone()

# print(ret[1])

8.事务锁

# begin;  # 开启事务

# select * from emp where id = 1 for update;  # 查询id值,for update添加行锁;

# update emp set salary=10000 where id = 1; # 完成更新

# commit; # 提交事务

 

# name = input("用户名:")

# worklock_list = [‘begin‘,‘select * from userinfo where name = "%s" for update‘%name,‘update userinfo set password = "Iloveu" where id = 1‘]

# for work in worklock_list:

#     cur.execute(work)

# # conn.commit()

# # print(‘修改完成!‘)

# sql = ‘select * from userinfo where id=1‘

# cur.execute(sql)

# print(cur.fetchone()[2])

# conn.commit()

 

9.关闭调用

调用完数据库,最后需要关闭调用的游标/链接

cur.close()

conn.close()

Mysql在python中的使用:pymysql

标签:添加   key   man   error:   bsp   nec   完数   ctc   error   

原文地址:https://www.cnblogs.com/sewen-H/p/13213382.html

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