博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
使用 pymysql 操作MySQL数据库
阅读量:7042 次
发布时间:2019-06-28

本文共 2894 字,大约阅读时间需要 9 分钟。

安装PyMySQL

是一个Python编写的MySQL驱动程序,让我们可以用Python语言操作MySQL数据库。

首先,使用pip安装PyMySQL。

pip install PyMySQL

使用PyMySQL

简单使用

如果有JDBC等其他语言的数据库学习经验的话,使用PyMySQL非常简单。下面是一个完整的MySQL增删查(没有改)的例子。

import pymysqlimport datetimehost = 'localhost'username = 'root'password = '12345678'db_name = 'test'create_table_sql = """\CREATE TABLE fuck(id INT AUTO_INCREMENT PRIMARY KEY,username VARCHAR(255) UNIQUE ,nickname VARCHAR(255) NOT NULL ,birthday DATE)"""insert_table_sql = """\INSERT INTO fuck(username,nickname,birthday) VALUES('{username}','{nickname}','{birthday}')"""query_table_sql = """\SELECT id,username,nickname,birthdayFROM fuck """delete_table_sql = """\DELETE FROM fuck """drop_table_sql = """\DROP TABLE fuck"""connection = pymysql.connect(host=host,                             user=username,                             password=password,                             charset='utf8mb4',                             db=db_name)try:    with connection.cursor() as cursor:        print('--------------新建表--------------')        cursor.execute(create_table_sql)        connection.commit()        print('--------------插入数据--------------')        cursor.execute(            insert_table_sql.format(username='yitian', nickname='易天', birthday=datetime.date.today()))        cursor.execute(            insert_table_sql.format(username='zhang3', nickname='张三', birthday=datetime.date.today()))        cursor.execute(            insert_table_sql.format(username='li4', nickname='李四', birthday=datetime.date.today()))        cursor.execute(            insert_table_sql.format(username='wang5', nickname='王五', birthday=datetime.date.today()))        connection.commit()        print('--------------查询数据--------------')        cursor.execute(query_table_sql)        results = cursor.fetchall()        print(f'id\tname\tnickname\tbirthday')        for row in results:            print(row[0], row[1], row[2], row[3], sep='\t')        print('--------------清除数据--------------')        cursor.execute(delete_table_sql)        connection.commit()        print('--------------删除表--------------')        cursor.execute(drop_table_sql)        connection.commit()finally:    connection.close()

如果需要更详细的资料,请查阅或者其他资料。

防止SQL注入

在上面的例子中直接拼接字符串,这不是好办法,因为可能存在SQL注入攻击,更好的解决办法是使用类库提供的函数来传参。所以上面的代码也需要稍作修改。

首先,将带参数的SQL语句改写。

insert_table_sql = """\INSERT INTO fuck(username,nickname,birthday) VALUES(%s,%s,%s)"""

然后将相应的执行代码也进行修改,execute函数接受一个元组作为SQL参数。所以代码改写为这样。

print('--------------插入数据--------------')cursor.execute(insert_table_sql, ('yitian', '易天', datetime.date.today()))cursor.execute(insert_table_sql, ('zhang3', '张三', datetime.date.today()))cursor.execute(insert_table_sql, ('li4', '李四', datetime.date.today()))cursor.execute(insert_table_sql, ('wang5', '王五', datetime.date.today()))connection.commit()

这样,SQL操作就更安全了。如果需要更详细的文档参考吧。不过好像这些SQL数据库的实现还不太一样,PyMySQL的参数占位符使用%s这样的C格式化符,而Python自带的sqlite3模块的占位符好像是?。因此在使用其他数据库的时候还是仔细阅读文档吧。

转载地址:http://hqhal.baihongyu.com/

你可能感兴趣的文章
Microsoft Visual C++ 9.0 is required Unable to find vcvarsall.bat 解决办法
查看>>
【转】ASP.NET中验证控件的使用
查看>>
搭建和测试 Redis 主备和集群
查看>>
Android应用资源
查看>>
app开发中如何利用sessionId来实现服务端与客户端保持回话
查看>>
swift学习笔记(五)构造过程
查看>>
es67
查看>>
浅谈 trie树 及事实上现
查看>>
sklearn特征抽取
查看>>
Android中加入思源字体/NotoSansCJK/SourceHanSans
查看>>
Ionic2 下处理 Android 设备下返回按钮的事件
查看>>
Linux时间子系统之(二):软件架构
查看>>
低调、奢华、有内涵的敏捷式大数据方案:Flume+Cassandra+Presto+SpagoBI
查看>>
八皇后问题java实现
查看>>
权限管理系统---の数据库
查看>>
抽象工厂模式(Java与Kotlin版)
查看>>
树莓派解决待机问题
查看>>
How to suppress 'Maybe this is program method' warnings from ProGuard
查看>>
基于灰度世界、完美反射、动态阈值等图像自动白平衡算法的原理、实现及效果...
查看>>
jquery获取input值的各种情况
查看>>