远程连接MySQL数据库(多种方法)
在这个例子中,我们将使用Python语言和MySQL-connector库来演示如何连接到远程MySQL数据库。
方法一:使用MySQL-connector库
import mysql.connector
config = {
'user': 'username',
'password': 'password',
'host': '192.168.1.xx',
'database': 'database_name',
'raise_on_warnings': True
}
try:
connection = mysql.connector.connect(**config)
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 error:
print("Failed to connect to database: {}".format(error))
finally:
if (connection.is_connected()):
cursor.close()
connection.close()
print("MySQL connection is closed")
方法二:使用PyMySQL库
import pymysql
db = pymysql.connect("192.168.1.xx","username","password","database_name")
cursor = db.cursor()
cursor.execute("SELECT VERSION()")
data = cursor.fetchone()
print ("Database version : %s " % data)
db.close()
方法三:使用SQLAlchemy库
from sqlalchemy import create_engine
engine = create_engine('mysql+mysqlconnector://username:password@192.168.1.xx:3306/database_name')
connection = engine.connect()
print("Connection established")
result = connection.execute("SELECT 1")
print(result.fetchone())
connection.close()
以上代码都是使用Python连接到远程MySQL数据库,你可以根据自己的需求选择合适的方法。在实际应用中,你需要替换'username', 'password', '192.168.1.xx', 'database\_name'为你自己的数据库连接信息。
评论已关闭