操控MySQL数据库

Python想要操控MySQL,先要安装库,在Python3.x下,该包名为MySQLclient。

安装,在cmd中运行:pip install MySQLClient
 
使用流程:
导入包-->创建Connection-->获取Cursor-->……-->关闭Cursor-->关闭Connection
 
首先确保MySQL服务器是启动状态。
导入包:import MySQLdb
创建Connection:创建Python与MySQL数据库之间的网络通路。
conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='mysql',db='zyq',charset='utf8')
参数:
host        String   服务器地址
port        int        端口
user        String   用户名
passwd   String    密码
db          String    数据库名
charset    String   连接字符集
 
支持的方法:
cursor()     创建并返回游标
commit()    提交当前命令
rollback()   回滚当前命令
close()      关闭Connection
 
获取游标:游标对象,用于执行查询和获取结果。
cur=conn.cursor()
 
支持方法:
execute()            用于执行一个数据库的查询命令
fetchone()           获取结果中的下一行
fetchmany(size)   获取结果中的下(size)行
fetchall()            获取结果集中的剩下的所有行
rowcount            最近一次execute返回数据/影响的行数
close()                关闭游标
 
例:
import MySQLdb
conn=MySQLdb.connect(host='127.0.0.1',port=3306,user='root',passwd='mysql',db='zyq',charset='utf8')
cur=conn.cursor()
sql="select * from kuandaizhanghao"
cur.execute(sql)
print(cur.rowcount)
rs=cur.fetchone()
print(rs)
cur.close()
conn.close()
posted @ 2020-11-07 07:31  隐泉  阅读(83)  评论(0编辑  收藏  举报