python 连接mysql
2018-06-17 本文已影响0人
任我笑笑
但是,在下面这个url里使用了pymysql,不知道跟上面廖雪峰的官方驱动是什么关系
https://blog.csdn.net/u011321546/article/details/78462035
然后在这个url里找到了答案
https://www.yoheim.net/blog.php?q=20151102
github地址
https://github.com/PyMySQL/PyMySQL/
里面给了一个经典的例子
try:
with connection.cursor() as cursor:
# Create a new record
sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
# connection is not autocommit by default. So you must commit to save
# your changes.
connection.commit()
with connection.cursor() as cursor:
# Read a single record
sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
cursor.execute(sql, ('webmaster@python.org',))
result = cursor.fetchone()
print(result)
finally:
connection.close()
不得不说,with xx as 看起来还真是优雅,自己close
但是外层的connection就只能手动用finally 来关掉了
更通俗的写法
conn =pymysql.connect(host='127.0.0.1', port=3307, user='root', passwd='usbw',db='test')
cursor = conn.cursor()
# 创建user表:
cursor.execute('create table user (id varchar(20) primary key, name varchar(20))')
# 插入一行记录,注意MySQL的占位符是%s:
cursor.execute('insert into user (id, name) values (%s, %s)', ['1', 'Michael'])
cursor.rowcount
# 提交事务:
conn.commit()
cursor.close()
# 运行查询:
cursor = conn.cursor()
cursor.execute('select * from user where id = %s', ('1',))
values = cursor.fetchall()
print(values)
cursor.close()
conn.close()