import pymysql #记得导库 pymysql
#连接数据库(localhost(本地数据库可填写localhost),账号,密码,库名)
db = pymysql.connect("localhost","name","password","zhongm" )
# 获取游标(游标可操作sql语句)
cursor = db.cursor()
#创建表的sql语句, not null 表示该字段不能为空, auto_increment表示自增长
createtable = """create table name_info(
id int (11) not null AUTO_INCREMENT,
name varchar(50) not null,
age int(10) not null,
primary key(id)) DEFAULT CHARSET=utf8 AUTO_INCREMENT=0
"""
#执行创建表的语句
cursor.execute(createtable)
# 插入数据,一般插入数据用execute(), 如果插入多条数据则使用executemany()
#cursor.execute("insert into name_info(name, age) VALUE ('mazi', '20')") #插入单条数据
cursor.executemany("insert into name_info(name, age) VALUE (%s, %s)", (('zhangsan',23),('lisi',28),('wanger',40)))
#查询
#执行sql语句
cursor.execute("select * from name_info")
#拿到查询出来的结果
request = cursor.fetchall()
#打印查询到的所有结果
for row in request:
id = row[0]
name = row[1]
age = row[2]
print(id, name, age)
#删除
deleteSQL = "delete from name_info where name = 'zhangsan'"
cursor.execute(deleteSQL)
#提交数据,不然数据不会生效 commit()
db.commit()
#最后需要关闭连接,不然会造成资源占用过多,导致内存溢出
db.close()
python+myslq数据库从连接到创建表,以及数据库基本的增删查改
最新推荐文章于 2025-05-07 18:21:22 发布