我正在尝试将位于Web服务器上的数据库连接到机器人,但我不知道如何将数据库连接到机器人。我希望机器人能够从机器人运行SELECT和UPDATE查询。另一个问题是我不打算使用C语言或Java;我计划在主控制系统中使用python。
我知道: PHP VBScript中 批量 蟒
如果有人知道如何将数据库连接到机器人,那将是一个很大的帮助。
答案 0 :(得分:0)
那么基本上如何在python中连接到SQL DB?我现在正在做一个虚拟机器人做同样的事情。查看模块,SQL-connector!
http://www.mysqltutorial.org/python-connecting-mysql-databases/
您将首先使用凭证
[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 ***')