MySQL 是一种广泛使用的关系型数据库管理系统(RDBMS),它允许开发者通过 SQL 语言来存储、管理和检索数据。以下是一个基本的 MySQL 本地数据库连接代码示例,使用 Python 语言和 mysql-connector-python
库来实现连接。
以下是一个使用 Python 连接本地 MySQL 数据库的示例代码:
import mysql.connector
# 连接数据库
try:
connection = mysql.connector.connect(
host="localhost", # 数据库主机地址
user="your_username", # 数据库用户名
password="your_password",# 数据库密码
database="your_database" # 要连接的数据库名
)
if connection.is_connected():
db_info = connection.get_server_info()
print("Connected to MySQL Server version ", db_info)
cursor = connection.cursor()
cursor.execute("select database();")
record = cursor.fetchone()
print("You're connected to database: ", record)
except mysql.connector.Error as e:
print("Error while connecting to MySQL", e)
finally:
if connection.is_connected():
cursor.close()
connection.close()
print("MySQL connection is closed")
systemctl status mysql
查看 MySQL 服务状态。/var/log/mysql/error.log
,可以帮助诊断问题。my.cnf
或 my.ini
)以允许远程连接或调整其他设置。通过以上步骤,你应该能够解决大多数基本的连接问题。如果问题依然存在,可能需要更详细的错误信息来进行进一步的排查。
领取专属 10元无门槛券
手把手带您无忧上云