跳到正文

Python中操作mysql的pymysql模块详解

Python 2076 次浏览

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(<span class="hljs-string">'--------------插入数据--------------'</span>)
    cursor.execute(
        insert_table_sql.format(username=<span class="hljs-string">'yitian'</span>, nickname=<span class="hljs-string">'易天'</span>, birthday=datetime.date.today()))
    cursor.execute(
        insert_table_sql.format(username=<span class="hljs-string">'zhang3'</span>, nickname=<span class="hljs-string">'张三'</span>, birthday=datetime.date.today()))
    cursor.execute(
        insert_table_sql.format(username=<span class="hljs-string">'li4'</span>, nickname=<span class="hljs-string">'李四'</span>, birthday=datetime.date.today()))
    cursor.execute(
        insert_table_sql.format(username=<span class="hljs-string">'wang5'</span>, nickname=<span class="hljs-string">'王五'</span>, birthday=datetime.date.today()))
    connection.commit()

    print(<span class="hljs-string">'--------------查询数据--------------'</span>)
    cursor.execute(query_table_sql)
    results = cursor.fetchall()
    print(<span class="hljs-string">f'id\tname\tnickname\tbirthday'</span>)
    <span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> results:
        print(row[<span class="hljs-number">0</span>], row[<span class="hljs-number">1</span>], row[<span class="hljs-number">2</span>], row[<span class="hljs-number">3</span>], sep=<span class="hljs-string">'\t'</span>)

    print(<span class="hljs-string">'--------------清除数据--------------'</span>)
    cursor.execute(delete_table_sql)
    connection.commit()

    print(<span class="hljs-string">'--------------删除表--------------'</span>)
    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自带的sqlite3模块的占位符好像是?。因此在使用其他数据库的时候还是仔细阅读文档吧。

      </div>
    </div>
</div>






  
    <div id="free-reward-panel" class="support-author"><p>小礼物走一走,来简书关注我</p></div></div><br><br>作者:乐百川<br>链接:https://www.jianshu.com/p/7d23da5b904e<br>來源:简书<br>著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。</div>

评论

加载中…