
在学习python过程中,熟练掌握数据库使用是非常重要的,python对接多种数据库,如:GadFly、mSQL、MySQL、PostgreSQL等等,想要了解访问MySQL数据库,可以看下面使用流程: 一、链接数据库 conn = pymysql.connect(host='127.0.0.1', port=3306, user='school_spt', passwd='123456', db='school_info') #返回个链接对象 二、创建游标 cursor = conn.cursor() 三、sql拼接命令 1.字符串拼接(不推荐使用该方式,容易被sql注入) user='root'
pwd='123456'
sql='select * from userinfo where password=%s and username=%s'%(pwd,user) 2.pymysql命令自带拼接 executsql命令, args) #args可以是列表,元组或者字典
列表:
user='root'
pwd='123456'
sql='select * from userinfo where password=%s and username=%s'
cursor.execute(sql,[pwd,user])
元组
user='root'
pwd='123456'
sql='select * from userinfo where password=%s and username=%s'
cursor.execute(sql,(pwd,user))
字典
sql='select * from userinfo where password=%(password)s and username=%(username)s'
cursor.execute(sql,({'password':pwd,'username':user})) 四、查 sql='select * from userinfo'
res=cursor.execute(sql) #返回受影响的行数
#获取返回的数据
cursor.fetchone() #获取返回的第一行内容
cursor.fetchmany(n) #获取返回的前n行内容
cursor.fetchall() #获取返回的全部内容
#返回的数据默认是元组形式,如果要以字典形式显示
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor) 五、改(改,删,增) 1.增 sql=‘insert into userinfo(username,password) values(%s,%s)’
cursor.execute(sql,('root','123')); #单条插入
也可以使用批量插入数据
cursor.executemany(sql,[('root','123'),('root1','1234'),('root2','123')]); 2.改,删没有批量执行命令,批量一般都使用单条执行 3.增,删,改操作后,都需要使用 conn.commit()来确认提交数据 六、execute会返回受影响的行数。一般不适用 七、scroll 在fetch数据时按照顺序进行(类似生成器),可以使用cursor.scroll(num,mode)来移动游标位置,如: cursor.scroll(1,mode='relative') # 相对当前位置移动
cursor.scroll(2,mode='absolute') # 相对绝对位置移动 八、获取最后的自增id值(lastrowid) id=cursor.lastrowid 九、关闭游标和链接 cursor.close() #先关闭游标
conn.close() #再关闭连接 MySQL 是一种关联数据库管理系统,关联数据库将数据保存在不同的表中,能够增加速度并提高灵活性,是很广泛的适应于日常工作的,大家可以尝试学习下啊~ 更多python实用知识,点击进入PyThon学习网教学中心。 |