Python与SQL:如何进行数据交互?

原创 男娘i 2025-02-04 19:54 42阅读 0赞

在Python中与SQL进行数据交互,通常涉及到数据库连接、查询执行和结果处理等步骤。这里以MySQL为例介绍基本操作:

  1. 安装必要的库

    • 如果还没有安装pymysql(Python 3)或者mysql-connector-python(Python 2),可以使用pip进行安装:
      1. pip install pymysql
      2. # 对于Python 2,需要安装mysql-connector-python
  2. 建立数据库连接

    1. import pymysql
    2. # 创建连接对象
    3. db = pymysql.connect(host='localhost', # 指定MySQL服务器地址
    4. user='username', # 指定用户名
    5. password='password', # 指定密码
    6. database='database_name' # 指定数据库名称
    7. )
    8. cursor = db.cursor() # 创建游标对象
    9. # 关闭连接
    10. db.close()
  3. 执行SQL查询

    1. # 基于之前的数据库连接,执行查询
    2. query = "SELECT * FROM table_name;"
    3. try:
    4. cursor.execute(query)
    5. results = cursor.fetchall() # 获取所有数据
    6. for row in results:
    7. print(row)
    8. except Exception as e:
    9. print(f"Error executing query: {e}")
    10. finally:
    11. if cursor:
    12. cursor.close()
    13. db.close()

以上步骤中,你需要替换localhostusernamepasswordtable_name为你实际的数据库信息。

文章版权声明:注明蒲公英云原创文章,转载或复制请以超链接形式并注明出处。

发表评论

表情:
评论列表 (有 0 条评论,42人围观)

还没有评论,来说两句吧...

相关阅读