import mysql.connector
from mysql.connector import errorcode
connection_config = {
"user": "用户名",
"password": "密码",
"host": "ip地址",
"database": "数据库名"
}
values02 = {} #在Python中搜索到的mysql数据是由元组组成的list列表,所以存放的时候设定值的属性为list属性,也可以不用设置;
values01 = {}
values03 = {}
try:
cnx = mysql.connector.connect(**connection_config)
# fetchwarings的应用-----01
cnx.get_warnings = True #fetchwaring()使用时必须要设置的参数,默认是false
cursor = cnx.cursor()
cursor.execute("select 'a'+1;")
print(cursor.fetchall())
print(cursor.fetchwarnings())
print("#############################")
# -----01
query01 = "select 【任何格式的字段】,DATE_FORMAT(【时间格式的字段名】,'%Y-%m-%d') from 【表名】 limit 3;"
cursor.execute(query01)
# 第一种fetchone()应用-----02
row01 = cursor.fetchone()
while row01 is not None:
print(row01)
row01 = cursor.fetchone()
print("############################")
# -----02
# 第二种fetchone()应用-----03
query02 = "select DATE_FORMAT(【时间格式的字段名】,'%Y-%m-%d') from 【表名】 limit 4;"
cursor.execute(query02)
for row02 in cursor:
print(row02)
print("############################")
# -----03
# fetchmany()应用-----04
query03 = "select 【字段名】 from 【表名】 limit 5;"
cursor.execute(query03)
values01 = cursor.fetchmany(size=2)
print(values01)
# -----04
# fetchall()应用------05
values02 = cursor.fetchall()
print(values02)
print("Warning: 开始-- {} --结束".format(cursor.fetchwarnings()))
# -----05
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print("Something is wrong with your user name or password.")
print(err)
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print("Database does not exists!")
else:
print("Error:")
print(err)
else:
cursor.close()
cnx.close()
# for i in values02:
# print(i)
# fetchmany()函数:默认抓出检索出的数据的第一行数据;括号里增加一个size=n的值,它就会抓出前n条记录。
# fetchone()函数: 默认抓出检索出的数据的一行,可以使用while语句循环抓取,也可以将cusor作为迭代器抓取;
# #注:如果用同一个连接对象去执行新的sql语句,必须要让这个fetchone()函数抓取完它本该显示的所有数据才能被下一个sql使用其用过的连接对象。
# fetchall()函数:默认抓取检索到的所有行数据信息,一次性获取;
# fetchwarning()函数:可以抓取到警告的信息,需要对生成的连接对象做一次开放动作。
以上的信息的参考来自与官网提供的example。
地址为:https://dev.mysql.com/doc/connector-python/en/connector-python-api-mysqlcursor-fetchwarnings.html