[python学习记录]python初步操作mysql

这篇博客记录了Python连接MySQL数据库的基本操作,包括加参数和不加参数的元组及字典形式,以及如何创建表、插入数据。重点介绍了`execute()`和`executemany()`的区别,前者用于执行单次SQL语句,后者则能一次性处理多个数据插入。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据库的连接

import MySQLdb
# 创建连接对象里面,除了port必须是整数型,其余全是字符类型
conn = MySQLdb.connect(host = 'localhost',port = 3306,user = 'root',password = '123456',db = 'first_db',charset = 'utf8')
# 如果想在后面执行sql语句获取的结果是字典的形式,在获取cursor对象时传递MySQLdb.cursors.DictCursor值给cursorclass参数即可
cursor = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor)
# 而如果不传,则默认操作结果为元组的方式,即:
cursor = conn.cursor()
sql = 'show databases'
cursor.execute(sql)
da = cursor.fetchone()      #取一条结果
db = cursor.fetchall()      #取全部结果
print(da)
print(db)
# 关闭数据库连接时要关闭数据库交互对象cursor与数据库连接对象connection
cursor.close()
conn.close()

加参数和不加参数返回的元组和字典形式如下:

#元组形式,一个元组里面嵌套元组
C:\Users\Administrator\Desktop\pythonsou>D:/pythonI-nstall/python.exe c:/Users/Administrator/Desktop/pythonsou/7_18/save_to_db.py
('first_db',)
(('information_schema',), ('mysql',), ('performance_schema',), ('sakila',), ('sys',), ('world',))
#字典形式
C:\Users\Administrator\Desktop\pythonsou>D:/pythonI-nstall/python.exe c:/Users/Administrator/Desktop/pythonsou/7_18/save_to_db.py
{'Database': 'first_db'}
({'Database': 'information_schema'}, {'Database': 'mysql'}, {'Database': 'performance_schema'}, {'Database': 'sakila'}, {'Database': 'sys'}, {'Database': 'world'})

建表,插入数据:

sql_creat_table = '''create table weather (pro_id int primary key auto_increment,
                     city varchar(10),
                     distract varchar(20),
                     bright_tianqi varchar(20),
                     bright_fengji varchar(20),
                     bright_highest varchar(10),
                     night_tianqi varchar(20),
                     night_fengji varchar(20),
                     night_lowest varchar(10))'''
try:
    cursor.execute('drop table if exists weather')
    #执行sql语句建表
    cursor.execute(sql_creat_table)
    print('creat table success!')
except Exception as e:
    print('sorry,creat table failed:')
    print(e)

插入数据:
cursor.execute(sql,list_or_tuple)
其中sql为要执行的插入语句,list_or_tuple表示要插入的数据可以使列表或者元组的方式组织的数据,如下所示:

#values里面必须是占位符%s,而且不管要插入的数据是字符还是数字,都只能用%s
#values里面有8个占位符,表示8个参数,那么cursor.executemany(sql_insert,list_total)中
#list_total这个列表里面就要有8个元素相对应
sql_insert = '''insert into weather(city,distract,''bright_tianqi,bright_fengji,
                bright_highest,night_tianqi,night_fengji,night_lowest) 
                values (%s,%s,%s,%s,%s,%s,%s,%s)'''
# 写入数据库
list_total = []
for province in dict_weather.keys():
    for distract in dict_weather[province].keys():
        list_item = [province]
        list_item.append(distract)
        list_item += dict_weather[province][distract][0] + dict_weather[province][distract][1]
        list_total.append(list_item)
# 这里有execute()和extcutemany()两个方法来进行插入,区别见后面解释
cursor.executemany(sql_insert,list_total)
print('done!')
cursor.close()
# 一定要提交才能写入到数据库中
conn.commit()
conn.close()

区别:execute()方法单一的执行一次sql语句,而后面的参数也只能供一次插入的数量,如[1,2,3,4]这种;而executemany()方法可以为这种数据[[1,2,3,4],[‘a’,‘b’,‘c’,‘d’]],如sql语句每次插入四个值,不用循环的方式将这8个值一次性插入进去。

参考https://www.cnblogs.com/aestheticism/p/5064998.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值