如何安全地将SQL数据库连接到外部客户端?
问题描述:
我试图将位于Web服务器上的数据库连接到机器人,但我不知道如何将数据库连接到机器人。我想让机器人运行机器人的SELECT和UPDATE查询。另一个问题是我不打算使用C语言或Java;我计划在主控制系统中使用python。如何安全地将SQL数据库连接到外部客户端?
我知道: PHP 的VBScript 批 的Python
如果有人知道如何将DB连接到机器人这将是一个很大的帮助。
答
那么基本上如何连接到SQL DB中的Python?我正在制作一个虚拟机器人,现在正在做同样的事情。看看模块,SQL连接器!
http://www.mysqltutorial.org/python-connecting-mysql-databases/
你会开始与您的凭据创建的config.ini
[mysql]
host = localhost
database = python_mysql
user = root
password =
阅读的Config.ini,并返回一个字典
from configparser import ConfigParser
def read_db_config(filename='config.ini', section='mysql'):
""" Read database configuration file and return a dictionary object
:param filename: name of the configuration file
:param section: section of database configuration
:return: a dictionary of database parameters
"""
# create parser and read ini configuration file
parser = ConfigParser()
parser.read(filename)
# get section, default to mysql
db = {}
if parser.has_section(section):
items = parser.items(section)
for item in items:
db[item[0]] = item[1]
else:
raise Exception('{0} not found in the {1} file'.format(section, filename))
return db
,并连接到MYSQL数据库
from mysql.connector import MySQLConnection, Error
from python_mysql_dbconfig import read_db_config
def connect():
""" Connect to MySQL database """
db_config = read_db_config()
try:
print('Connecting to MySQL database...')
conn = MySQLConnection(**db_config)
if conn.is_connected():
print('connection established.')
else:
print('connection failed.')
except Error as error:
print(error)
finally:
conn.close()
print('Connection closed.')
if __name__ == '__main__':
connect()
和更新声明看起来像下面
def update_book(book_id, title):
# read database configuration
db_config = read_db_config()
# prepare query and data
query = """ UPDATE books
SET title = %s
WHERE id = %s """
data = (title, book_id)
try:
conn = MySQLConnection(**db_config)
# update book title
cursor = conn.cursor()
cursor.execute(query, data)
# accept the changes
conn.commit()
except Error as error:
print(error)
finally:
cursor.close()
conn.close()
if __name__ == '__main__':
update_book(37, 'The Giant on the Hill *** TEST ***')
这是你在找什么? – Pacified