[英]How can I connect python to MySQL server
I coded a CRUD Python API with flask and MySQL.我用 flask 和 Z62A004B957946BB97541AFA7 编写了一个 CRUD Python API The source code is located in local system and the MySQL database is located on a real network host.
源代码位于本地系统,MySQL 数据库位于真实网络主机上。
Is it possible to connect local python code to MySQL on a real network host?是否可以将本地 python 代码连接到真实网络主机上的 MySQL ?
here is config.py这是 config.py
from app import app
from flask_mysqldb import MySQL
mysql = MySQL()
app.config['MYSQL_HOST'] = 'http://test.com:5000'
app.config['MYSQL_USER'] = 'guest'
app.config['MYSQL_PASSWORD'] = '12345'
app.config['MYSQL_DB'] = 'school'
mysql.init_app(app)
main.py:主要.py:
from flask import request, jsonify, redirect, url_for
from app import app
from config import MySQL
@app.route('/list')
def home():
try:
cursor = mysql.connection.cursor()
cursor.execute("SELECT * FROM student")
row_headers = [x[0] for x in cursor.description]
studentsRows = cursor.fetchall()
json_data = []
for result in studentsRows:
json_data.append(dict(zip(row_headers, result)))
response = jsonify(student_list=json_data, status=120)
response.status_code = 200
return response
except Exception as e:
print(e)
@app.errorhandler(404)
def not_found(error=None):
message = {
'status': 404,
'message': 'Record not found: ' + request.url,
}
response = jsonify(message)
response.status_code = 404
return response
if __name__ == '__main__':
app.run(host="0.0.0.0")
It's definitely possible to connect from different location to your database.绝对可以从不同的位置连接到您的数据库。
It's actually the main feature of server based database systems as what mysql or for example postgresql is.它实际上是基于服务器的数据库系统的主要特征,就像 mysql 或例如 postgresql 一样。 Compare that to something like sqlite which is a simple file based database system.
将其与 sqlite 之类的东西进行比较,后者是一个简单的基于文件的数据库系统。
There is but a simple requirement to it - the server has to be network accessible from your current network.它有一个简单的要求 - 服务器必须可以从您当前的网络访问。
This means few things:这意味着几件事:
Please see the mysql manual , also there is a bunch of tutorials how to setup this, simple google search should work.请参阅mysql 手册,还有一堆教程如何设置,简单的谷歌搜索应该可以工作。
EDIT: As to your code example, please see flask_mysql documentation on how to connect to server, you will probably be most interested in the 'MYSQL_HOST'
value, though all the other values (user, pass, port, dbname) have to match what is configured on your server.编辑:至于您的代码示例,请参阅flask_mysql文档以了解如何连接到服务器,您可能对
'MYSQL_HOST'
值最感兴趣,尽管所有其他值(用户、通行证、端口、dbname)都必须匹配在您的服务器上配置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.