如何使用Python与Mysql进行数据交互

2018-07-10  本文已影响0人  ArthurSlog
ArthurSlog

自己的梦想需要你自己去实现

开发环境MacOS(High Sierra 10.13.5)

python

在Mysql的官网获取Python与Mysql的交互手册Mysql官方手册

This manual describes how to install and configure MySQL Connector/Python, a self-contained Python driver for communicating with MySQL servers, and how to use it to develop database applications.

pythontodatabase.py

import mysql.connector

cnx = mysql.connector.connect(user='root', password='661475chen', host='127.0.0.1', database='my_db')
cursor = cnx.cursor()

query = ("SELECT * FROM Account ")

cursor.execute(query)

for (ID, AccountName, Password) in cursor:
  print("{}, {}, {}".format(
    ID, AccountName, Password))

cursor.close()
cnx.close()
  1. 导入Mysql/Python-Connector模块,import mysql.connector
  2. 连接数据库,获得返回值对象cnx(这个也就是与Mysql通信的对象),cnx = mysql.connector.connect()
  3. 获得cursor对象,这个是关键点,参考Python官方手册,cursor = cnx.cursor()
  4. 配置sql指令的对象,query = ("")
  5. 发送并执行sql指令,cursor.excute(query),这个也是关键点,参考Python官方手册
  6. 关闭cursor对象,cursor.close()
  7. 关闭通信对象,cnx.close()

python pythontodatabase.py

1 - ArthurSlog - ArthurSlog

欢迎关注我的微信公众号 ArthurSlog

ArthurSlog

如果你喜欢我的文章 欢迎点赞 留言

谢谢

上一篇 下一篇

猜你喜欢

热点阅读