python操作数据库(MySQL)

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() # 关闭连接

 

posted @ 2018-01-25 14:29  wang!!!  阅读(94)  评论(0编辑  收藏  举报