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()#关闭数据库连接