Python写入数据到MySql

缘由

最近在完善一个自己的小软件,其所有的数据都从维基百科获取,最近软件和API都完善了,但数据总是有部分获取失败!今天仔细研究了一下发现大部分数据是获取成功了,但没有写入数据库,且没有报错!这我就懵了,第一想法是换一个包,换了就perfect!我看网上有三种选择方式,我这里就试过两种方式!我这里就放出简单的插入操作代码,具体操作点击链接就可去菜鸟查看!

mysql-connector(推荐使用)

推荐选择这个,这一个没怎么毛病!数据都写入成功!我看简介好像这一个是官方推出的!

安装

pip3 install mysql-connector 

使用(以insert为例子)

import mysql.connector

mydb = mysql.connector.connect(
  host="localhost",
  user="root",
  passwd="123456",
  database="runoob_db"
)
mycursor = mydb.cursor()

sql = "INSERT INTO sites (name, url) VALUES (%s, %s)"
val = ("RUNOOB", "https://www.runoob.com")
mycursor.execute(sql, val)

mydb.commit()    # 数据表内容有更新,必须使用到该语句

print(mycursor.rowcount, "记录插入成功。")

报错

Authentication plugin ‘caching_sha2_password’ is not supported

import mysql.connector

db = mysql.connector.connect(
    host='host', 
    user='user', 
    passwd='password', 
    # Important!!!
    auth_plugin='mysql_native_password'
    # Important!!!
)

PyMySQL

这一个我数据获取成功,但写入不到数据库(多次测试,50到70条数据),且没有任何提示信息!有点懵!

安装

pip3 install PyMySQL

使用(以insert为例子)

#!/usr/bin/python3

import pymysql

# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )

# 使用cursor()方法获取操作游标 
cursor = db.cursor()

# SQL 插入语句
sql = """INSERT INTO EMPLOYEE(FIRST_NAME,
         LAST_NAME, AGE, SEX, INCOME)
         VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
try:
   # 执行sql语句
   cursor.execute(sql)
   # 提交到数据库执行
   db.commit()
except:
   # 如果发生错误则回滚
   db.rollback()

# 关闭数据库连接
db.close()

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *