Python------mysql数据库

时间:2021-09-25 00:21:07
import pymysql

#一、直接连接mysql数据库
'''
coon=pymysql.connect(host='192.168.*.*',user='root',password='12345',port=3306,db='t3',charset='utf8',autocommit=True)
#建立游标
cur=coon.cursor()
sql='select * from u'
#sql= 'insert into u(name,id,sex,age) values("cat",4,"它",12)'
cur.execute(sql)
#fetchall获取所有结果信息---返回二维元组;fetchone 获取一条数据---返回元组;fetchmany(2) 获取n条数据---返回元组
#print(cur.fetchall())
#print(cur.fetone())
#print(cur.fetchmany(2))
cur.close()
coon.close()
''' mysql 插入新数据(用变量传递的方式),sql中变量用%s占位,在执行语句中用元组传递
import pymysql

coon=pymysql.connect(host='192.168.204.**',user='root',password='mysql',port=3306,db='fqm',charset='utf8',autocommit=True)

#建立游标

cur=coon.cursor()

for i in range(1,5)
sql = 'insert into ta012(id,month,airline,fi,dep,arr) values(%s,"2020-03","HU","HU0004","ZYTX","ZPPP")'



cur.execute(sql,(i,))

cur.close()

coon.close()

#二、用函数形式操作mysql数据库(传递字典形式参数)

MYSQL_INFO = {
'host':'192.168.206.190',
'user':'root',
'password':'12345',
'port':3306,
'db':'T3',
'charset':'utf8',
'autocommit':'True'
}#数据库配置信息 def my_db(**kwargs):
host=kwargs.get('host')
user = kwargs.get('user')
password = kwargs.get('password')
port = kwargs.get('port')
db = kwargs.get('db')
charset = kwargs.get('charset')
autocommit = kwargs.get('autocommit')
print(host,user,password,port,db,charset,autocommit)
print(type(host))
coon = pymysql.connect(host=host, user=user, password=password, port=port, db=db, charset=charset,autocommit=autocommit)
# 建立游标
cur = coon.cursor()
sql = 'select * from u'
# sql= 'insert into u(name,id,sex,age) values("cat",4,"它",12)'
cur.execute(sql)
# fetchall获取所有结果信息---返回二维元组;fetchone 获取一条数据---返回元组;fetchmany(2) 获取n条数据---返回元组
print(cur.fetchall())
# print(cur.fetone())
# print(cur.fetchmany(2))
cur.close()
coon.close()
my_db(**MYSQL_INFO)