python操作数据库

python操作数据库

首先安装数据插件

c 复制代码
pip install pymysql
c 复制代码
from pymysql import  Connection  # 引入数据库第三方包

# 创建链接
conn = Connection(
    host="localhost", # 主机名ip
    port=3306,
    user="root",# 用户名
    password="123456"  # 密码
)

print(conn.get_server_info())  # 得到数据库版本  代表链接成功

cursor = conn.cursor()  # 获取游标对象
conn.select_db("test") # 选择数据库
# cursor.execute("create table ceshi( id int , name varchar(10),sex int);") # 创建数据表
cursor.execute("select * from student")  #  查询数据表
res:tuple=cursor.fetchall()  # 得到元祖类型的数据
for i in res:
    print(i)

conn.close() # 关闭数据库

数据库的插入

c 复制代码
from pymysql import Connection

# 创建链接
conn = Connection(
    host="localhost",  # 主机名ip
    port=3306,
    user="root",  # 用户名
    password="123456" , # 密码
    autocommit=True  # 自动提交 如果这里不自动提交 那么就需要在执行完毕后手动commit提交 如果不提交是不会生效的
)

print(conn.get_server_info())

cursor = conn.cursor()  # 获取游标对象
conn.select_db("test")  # 选择数据库
cursor.execute("insert into student values(10003,'临济',13,'女'),(10001,'临济2',13,'男')")
# conn.commit()

conn.close()
相关推荐
默 语1 天前
RAG实战:用Java+向量数据库打造智能问答系统
java·开发语言·数据库
北极糊的狐1 天前
若依报错org.springframework.dao.DataIntegrityViolationException
数据库·mysql
carver w1 天前
智能医学工程选题分享
python
醒过来摸鱼1 天前
Java Compiler API使用
java·开发语言·python
dazhong20121 天前
Mybatis 敏感数据加解密插件完整实现方案
java·数据库·mybatis
superman超哥1 天前
仓颉语言中字符串常用方法的深度剖析与工程实践
开发语言·后端·python·c#·仓颉
薛晓刚1 天前
2025 年度个人回顾总结
数据库
TDengine (老段)1 天前
TDengine 在智能制造领域的应用实践
java·大数据·数据库·制造·时序数据库·tdengine·涛思数据
癫狂的兔子1 天前
【BUG】【Python】精确度问题
python·bug
想学后端的前端工程师1 天前
【Spring Boot微服务开发实战:从入门到企业级应用】
java·开发语言·python