作者:mobiledu2502928897 | 来源:互联网 | 2024-11-12 16:51
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数据库(传递字典形式参数)
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)
Python------mysql数据库