python3 使用数据库(SQL命令大小写一样)

本文介绍了如何使用Python3的PyMySQL库连接数据库,创建表,插入数据,查询和更新数据。通过示例展示了SQL命令在Python中大小写不敏感的特性。

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

import pymysql//需要pip3 install PyMSQL

连接数据库,返回连接到的数据库db,和光标cursor

   cursor,db=connect_db()
   def connect_db():
    	db=pymysql.connect(host='127.0.0.1', 
    	#远程ip地址host='x.x.x.x',传到云端时修改为host='127.0.0.1'
    		port=3306, #数据库的端口号
    		user='name', #数据库用户名
    		passwd='pwd', #数据库用户密码
    		db='bd', #数据库名
    
    		)
    	cursor=db.cursor(cursor=pymysql.cursors.DictCursor)
    	##默认,通过光标获取的返回值是元组(4),只能看到每行数据,不知道每一列代表什么,使用该方式来返回字典,每一行的数据都会生成一个字典{"id":4}
    	return cursor,db

在数据库里创建一个表,有两个字段name,age

cursor.execute("drop table if exists biao")#如果数据库中已经有该名的表,删除它
sql="""create table biao(name char(20),
	age int(20)
	)"""
cursor.execute(sql)
db.commit()

在表中插入新字段

sql="alter table biao add (weight int(20))"
cursor.execute(sql)
db.commit()

在表中插入数据

sql="insert into biao (name, age) values('ming', 13)"
cursor.execute(sql)
db.commit()

查找单个内容:查找news表中id=4的title的值

sql='select title from news where id=4'#获取表中id=4的title列
cursor.execute(sql)
result=cursor.fetchone()#获得下一个查询结果

查找很多内容:查找new表中所有id的值

sql='select title from news'#获取表中title列
cursor.execute(sql)
result=cursor.fetchall()#接收全部的返回结果行
for re in result:
	xxx

更新数据:更新news表中所有的title值

for id in rang(1, 5, 1):#1开始,5之前结束,一次跳一步,为:1,2,3,4
	sql="update news set title='%s' where id=%d"%(string, id)
	try:
		cursor.execute(sql)
		db.commit()
		print("{}"写入成功).format(id)#({} {}).format(x,x)如同%
	except:
		#发生错误时回滚
		db.rollback()

结束时

db.close()#关闭数据库连接
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值