Python连接数据库

1. 安装环境,打开pycharm开发工具,新建python文件下载pymysql

pip install pymysql

2. python语句

  • 第1步:调用pymysql模块中的connect方法,连接mysql数据库。
  • 第2步:使用cursor()方法创建一个游标对象,然后赋值给cur。
  • 第3步:调用方法execute执行创建表t_kmn语句,先执行删除表,然后创建。
  • 第4步:再次调用execute方法,执行上述SQL语句。
  • 第5步:最后,调用close()方法,关闭数据库连接。
  • 第6步:保存代码并运行python文件,执行成功后,查看MySQL客户端是否生成t_kmn表。
复制代码
import pymysql
​
db = pymysql.connect(host='localhost',
                     user='user',
                     password='passwd',
                     db='db',
                     charset='utf8')
​
try:
    with db.cursor() as cursor:
        # 插入
        sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
        cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
    # 需要手动提交才会执行
    db.commit()
​
    with db.cursor() as cursor:
        # 读取记录
        sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
        cursor.execute(sql, ('webmaster@python.org',))
        result = cursor.fetchone()
        print(result)
finally:
    db.close()
复制代码

window端执行python语句,验证是否可连接至centos上数据库,并获取正确结果

复制代码
import pymysql

# host 指的是数据库服务器的主机地址
# user 连接数据库的用户

# 打开一个数据库的连接,获取一个db对象
# db = pymysql.connet()  # 结果是一个Connection类型的对象
# db.cursor()   获取到一个cursor对象,用它来操作数据库

db = pymysql.connect(host='172.18.20.225',user='moria',password='abcd1234',database='carlos_test2',port=3306,charset='utf8')
cursor = db.cursor()
cursor.execute('select * from student')
cursor.close()
db.commit()
db.close()

for info in cursor.fetchall():
    print(info)
复制代码

.......

posted on   CARLOS_KONG  阅读(21)  评论(0编辑  收藏  举报

相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 【译】Visual Studio 中新的强大生产力特性
· 【设计模式】告别冗长if-else语句:使用策略模式优化代码结构
· 10年+ .NET Coder 心语 ── 封装的思维:从隐藏、稳定开始理解其本质意义

导航

点击右上角即可分享
微信分享提示