 
- Python 和 MySQL 教程
- Python 和 MySQL - 主页
- Python 和 MySQL - 概述
- Python 和 MySQL - 环境设置
- Python 和 MySQL 示例
- Python 和 MySQL - 连接数据库
- Python 和 MySQL - 创建数据库
- Python 和 MySQL - 删除数据库
- Python 和 MySQL - 选择数据库
- Python 和 MySQL - 创建表
- Python 和 MySQL - 删除表
- Python 和 MySQL - 插入记录
- Python 和 MySQL - 选择记录
- Python 和 MySQL - 更新记录
- Python 和 MySQL - 删除记录
- Python 和 MySQL -Where 子句
- Python 和 MySQL - Like 子句
- Python 和 MySQL - 数据排序
- Python 和 MySQL - 使用联接
- Python 和 MySQL - 执行事务
- Python 和 MySQL - 处理错误
- Python 和 MySQL 有用资源
- Python 和 MySQL - 快速指南
- Python 和 MySQL - 有用的资源
- Python 和 MySQL - 讨论
Python 和 MySQL - 选择数据库示例
Python MySQLdb 提供MySQLdb.connect()函数来选择数据库。该函数接受多个参数并返回一个连接对象来执行数据库操作。
句法
db = MySQLdb.connect(host, username, passwd, dbName, port, socket);
| 先生。 | 参数及说明 | 
|---|---|
| 1 | 主持人 可选 - 运行数据库服务器的主机名。如果未指定,则默认值为localhost:3306。 | 
| 2 | 用户名 可选 - 访问数据库的用户名。如果未指定,则默认值将是拥有服务器进程的用户的名称。 | 
| 3 | 密码 可选 - 访问数据库的用户的密码。如果未指定,则默认密码为空。 | 
| 4 | 数据库名称 可选 - 要执行查询的数据库名称。 | 
| 5 | 港口 可选 - 尝试连接到 MySQL 服务器的端口号。 | 
| 6 | 插座 可选 - 应使用的套接字或命名管道。 | 
您可以随时使用另一个连接对象函数close()断开与 MySQL 数据库的连接。
句法
db.close()
例子
尝试以下示例连接到 MySQL 数据库 -
将以下示例复制并粘贴为 mysql_example.py -
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","root","root@123", "TUTORIALS")
# prepare a cursor object using cursor() method
cursor = db.cursor()
# execute SQL query using execute() method.
cursor.execute("SELECT VERSION()")
# Fetch a single row using fetchone() method.
data = cursor.fetchone()
if data:
   print('Version available: ', data)
else:
   print('Version not retrieved.')
# disconnect from server
db.close()
输出
使用 python 执行 mysql_example.py 脚本并验证输出。
py mysql_example.py
Version available:  ('8.0.23',)