python mysql github_GitHub上一个用Python写的MySQL库

https://github.com/PyMySQL/PyMySQL

PyMySQL:纯 pyton 写的 mysql 库,纯 python 的好处就是可以运行在任何装有 python 解释器(CPython、PyPy、IronPython)的平台上。相对于MySQLdb性能几乎一样,使用方法也一样,但是** PyMySQL 安装方法极其简单**——pip install PyMySQL,PyMySQL 使用示例代码:

# 下面为例子需要的数据库的建表语句

CREATE TABLE users (

id int( 11 ) NOT NULL AUTO_INCREMENT,

email varchar( 25 5) COLLATE utf8_bin NOT NULL,

password varchar( 255 ) COLLATE utf8_bin NOT NULL,

PRIMARY KEY ( id )

) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_bin

AUTO_INCREMENT=1 ;

# -*- coding: utf-8 -*-

import pymysql.cursors# 连接数据库

connection = pymysql.connect( host='localhost', user='user', password='passwd', db='db', charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor)

try:

with connection.cursor() as cursor:

# 创建一个新的纪录

sql="INSERT INTO users ( email, password )  VALUES (%s,%s)"

cursor.execute(sql, ('webmaster@python.org','very-secret'))

# 连接不会自动提交,所以你想下面要调用 commit 方法,存储对数据库的改动

connection.commit()

with connection.cursor() ascursor:

sql="SELECT id, password FROM users WHERE email=%s"cursor.execute(sql, ('webmaster@python.org',))

# 获取一条的纪录

result=cursor.fetchone()

print(result)

# 结果输出:{'password': 'very-secret', 'id': 1}

finally:

connection.close()

# 操作完数据库一要记得调用 close 方法,关闭连接

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值