Python MySQL操作

Python Mysql 操作步骤

1、安装pymysql安装包

pip install pymysql

2、导包

import pymysql

3、连接数据库

db=pymysql.connet(
    host=172.0.0.1,
    user="root",
    password="123456",
    database="xxx",
    character="utf8")

4、创建游标

cursor = db.cursor()

5、数据库操作

<!--创建表-->
sql = "CREATE TABLE IF NOT EXISTS `user`(
                    username VARCHAR(10) COMMENT '用户名',
                    passwd VARCHAR(32) COMMENT '密码'
                    ) ENGINE='INNODB' DEFAULT CHARSET='utf8mb4' COMMENT '用户表'"
cursor.execute(sql)

<!--删除表-->
sql = "drop table if exists %s"%table_name
cursor.execute(sql)

<!--查询数据-->
<!--获取单条数据:fetchone()-->
<!--获取多条数据:fetchall()-->
sql = "select *from table_name"
cursor.execute(sql)
result=cursor.fetchone()
results=cursor.fetchall()
<!--插入数据-->
sql="insert into user(username,password) value('james','123456')"
cursor.execute(sql)
<!--提交数据-->
db.commit()
<!--回滚操作-->
db.rollback()

<!--删除数据-->
sql="delete from user where username='james'"
cursor.execute(sql)
db.commit()
<!--修改数据数据-->
sql="update user set password='zhou123' where username='james' "
cursor.execute(sql)
db.commit()

6、关闭游标和连接

cursor.close()
db.close()

7、总结

 python pymysql对于msyql的操作原理实际上是基于执行sql语句,当修改数据时,需要commit操作,记住以上的操作步骤,其他的只需要学好sql语句就OK了

猜你喜欢

转载自www.cnblogs.com/zhouzhiwei/p/12961093.html
今日推荐