使用PyMySQL操作MySQL数据库

栏目: Python · 发布时间: 6年前

内容简介:使用PyMySQL操作MySQL数据库

安装PyMySQL

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

首先,使用pip安装PyMySQL。

pip install PyMySQL

使用PyMySQL

简单使用

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

import pymysql
import datetime

host = '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,birthday
FROM 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()

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

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

本文永久更新链接地址 http://www.linuxidc.com/Linux/2017-06/144690.htm


以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

PHP and MySQL Web Development

PHP and MySQL Web Development

Luke Welling、Laura Thomson / Sams / July 25, 2007 / $49.99

Book Description PHP and MySQL Web Development teaches you to develop dynamic, secure, commerical Web sites. Using the same accessible, popular teaching style of the three previous editions, this b......一起来看看 《PHP and MySQL Web Development》 这本书的介绍吧!

RGB转16进制工具
RGB转16进制工具

RGB HEX 互转工具

RGB HSV 转换
RGB HSV 转换

RGB HSV 互转工具

HEX CMYK 转换工具
HEX CMYK 转换工具

HEX CMYK 互转工具