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

python操作数据库(MySQL)

时间:2018-01-25 15:44:36      阅读:150      评论:0      收藏:0      [点我收藏+]

标签:仓库   端口号   values   python   必须   ble   连接数据库   utf8   pre   

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)

标签:仓库   端口号   values   python   必须   ble   连接数据库   utf8   pre   

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

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