python连接mysql,实现增删改查

python连接mysql需要以下五步:

  1. 连接数据库
  2. 生成游标对象
  3. 执行sql语句
  4. 关闭游标
  5. 关闭数据库连接

1. 连接数据库

准备:

​操作需要使用pymysql模块,第一进行下载:

​ ​pip install pymysql

​数据库:

​ ​create table user

​ ​(

​ ​ ​id int primary key auto_increment,

​ ​ ​name varchar(32),

​ ​ ​age int

​ ​)


import pymysql

#连接服务器地址(本机使用127.0.0.1)

host = '127.0.0.1'

#用户名

user = 'root'

#密码

password = '123456'

#端口(默认端口为3306)

port = 3306

#数据库名

db = 'mydb'

#字符编码

charset = 'utf8'

#创建连接

conn=pymysql.connect(host=host,user=user,password=password,port=port,db=db,charset=charset)

2. 生成游标对象

cursor = conn.cursor()

#设置参数 cursor=
pymysql.cursors.DictCursor 修改返回值类型为字典。默认为元组

3. 执行sql语句

​查询:(无参数)

​sql = “select * from user”

​rows = cursor.execute(sql) #执行sql语句并获得执行影响的行数

​data = cursor.fetchall() ​

​for item in data:

​ ​print(item)

​有参数(参数用元组传递)

​sql = “select * from from user where id=%s and name=%s”

​rows = cursor.execute(sql,(1,'张三'))

​data = cursor.fetchall()

增加:

try:

​​ ​sql = “insert into user values(null,'张三',16)”

​ ​rows = cursor.execute(sql)

​ ​conn.commit() #提交事务

​ except:

​ ​conn.rollback() #如果插入不成功,回滚事务

​另一种写法:

​try:

sql = “insert into user values(null,%s,%s)”

rows = cursor.execute(sql,('张三',16))

conn.commit() #提交事务

except:

conn.rollback() #如果插入不成功,回滚事务

​多行插入

​try:

sql = “insert into user values(null,%s,%s)”

​ ​data = [

​ ​(null,'张三',16),

​ ​ ​(null,'李四',23),

​ ​ ​(null,'王五',34)​

​ ​] #必须使用列表嵌套元组的形式

rows = cursor.executemany(sql,data)

conn.commit() #提交事务

except:

conn.rollback() #如果插入不成功,回滚事务

删除:

​try:

​ ​sql = “delete from user where id=%s”

​ ​rows = cursor.execute(sql,1)

​ ​conn.commit()

​except:

​ ​conn.rollback()

修改:

​try:

​ ​sql = “update user set name=%s where id=%s”

​ ​rows = cursor.execute(sql,('张五',1))

​ ​conn.commit()

​except:

​ ​conn.rollback()

4. 关闭游标

​cursor.close()

5. 关闭数据库连接

​conn.close()

© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容