MySQL支持两种主要的通信协议:TCP/IP协议和Unix域套接字协议。
/var/run/mysqld/mysqld.sock
或/tmp/mysql.sock
。my.cnf
或my.ini
)中的监听地址和端口设置。以下是一个使用Python连接到MySQL服务器的示例代码,分别使用TCP/IP协议和Unix域套接字协议:
import mysql.connector
config = {
'user': 'your_username',
'password': 'your_password',
'host': '127.0.0.1', # 或远程IP地址
'database': 'your_database',
'port': 3306,
'ssl_ca': '/path/to/ca.pem', # SSL证书路径
}
try:
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
cursor.execute("SELECT * FROM your_table")
for row in cursor:
print(row)
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
cnx.close()
import mysql.connector
config = {
'user': 'your_username',
'password': 'your_password',
'unix_socket': '/var/run/mysqld/mysqld.sock', # 或自定义套接字文件路径
'database': 'your_database',
}
try:
cnx = mysql.connector.connect(**config)
cursor = cnx.cursor()
cursor.execute("SELECT * FROM your_table")
for row in cursor:
print(row)
except mysql.connector.Error as err:
print(f"Error: {err}")
finally:
cursor.close()
cnx.close()
希望这些信息对你有所帮助!如果有更多具体问题,请随时提问。
领取专属 10元无门槛券
手把手带您无忧上云