首页 > 数据库技术 > 详细

python操作数据库(MySQL)

时间:2018-01-25 15:22:08      阅读:261      评论:0      收藏:0      [点我收藏+]

1、安装数据库MySQL

2、执行pip install pymysql 安装pymysql连接数据库

3、python连接数据库具体操作:

import pymysql

# 1、连接上mysql  ip 端口号  密码 账号 数据库
conn = pymysql.connect(host=‘123.456.789.00,
                       user=root, passwd=123456,  # port这里一定要写int类型
                       port=3306, db=test, charset=utf8) #charset必须写utf8,不能写utf-8

# 2、建立游标,游标你就认为是仓库管理员 cur = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 3、编写sql语句 sql = "INSERT INTO `table` ( `id`, `name`, `phone`, `addr`) VALUES (‘1‘, ‘mack‘, ‘18612341241‘, ‘北京‘);" sql = "select * from bt_stu limit 5;" sql = "select * from bt_stu where id=1;"

# 4、执行sql cur.execute(sql) # 执行sql语句 conn.commit() # 提交 # update delete insert 语句需要提交

# 5、获取sql语句执行的结果,它把结果放到一个元组里,每一条数据也是一个元组 res = cur.fetchall() # 获取全部 res = cur.fetchone() # 只获取一条结果,它的结果是一个1维元组
# 只有一条数据,那么就用fetchone,超过一条数据那就用fetchall
print(res) print(fetchall,cur.fetchall())

# 6、移动游标 cur.scroll(0,mode
=absolute)#移动游标,到最前面 cur.scroll(3,mode=relative)#移动游标,相对于当前位置的
# 7、关闭连接、关闭游标 cur.close() # 关闭游标 conn.close() # 关闭连接

 

python操作数据库(MySQL)

原文:https://www.cnblogs.com/wang-hao-yue/p/8351104.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!