python 连接mysql

2018-06-17  本文已影响0人  任我笑笑

基本的类似于jdbc的操作
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014320107391860b39da6901ed41a296e574ed37104752000

简单的orm 框架
https://www.liaoxuefeng.com/wiki/0014316089557264a6b348958f449949df42a6d3a2e542c000/0014320114981139589ac5f02944601ae22834e9c521415000

但是,在下面这个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()
上一篇下一篇

猜你喜欢

热点阅读