赞
踩
Python要想操作MYSQL,必须要有一个中间件(驱动程序),如:1.mysqldb(只在python2中有用)
2.mysqlclient
3.pymysql
这里以pymysql为例,安装方式可通过pip命令安装:pip install pymysql
可通过官网下载:https://dbeaver.io/download/
安装完成之后我们需要配置Maven镜像,这里提供阿里云镜像地址:http://maven.aliyun.com/nexus/content/groups/public
配置的方式为:窗口➡首选项➡输入框输入Maven➡添加镜像并置顶
配置镜像之后我们就可以连接数据库了,连接方式:
然后填写数据库连接信息
填写之后先点击测试连接,测试没问题之后就可以正式建立连接了
import pymysql
# 使用pymysql.connet方法连接数据库
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123")
# 建立游标,用于操作数据库
cursor = db.cursor()
# 使用cursor.execute来执行sql语句
cursor.execute("select * from biao1")
result = cursor.fetchone()
print(result)
db.commit() # 提交
db.close() #关闭
import pymysql
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123")
cursor = db.cursor()
sql = "insert into biao1(id,name) values('2','杨开')"
cursor.execute(sql)
sql2 = "insert into biao1(id,name) values(%s,%s)"
cursor.execute(sql2, ('004', '苏颜'))
db.commit()
db.close()
import pymysql db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123") cursor = db.cursor() sql = "select name from biao1" cursor.execute(sql) result = cursor.fetchone() print(result) result2 = cursor.fetchall() print(result2) result3 = cursor.fetchmany(3) print(result3) sql = "select id from biao1 where id>2" cursor.execute(sql) result = cursor.fetchall() print(result) db.commit() db.close()
import pymysql
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123")
cursor = db.cursor()
sql = "delete from biao1 where id=002"
cursor.execute(sql)
db.commit()
db.close()
import pymysql
db = pymysql.connect(host="localhost", port=3306, user="root", password="12345678", database="chen123", charset="utf8mb4")
cursor = db.cursor()
# update 表名 更新操作 条件
sql = "update biao1 set name='伏天' where id=003"
cursor.execute(sql)
db.commit()
db.close()
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。