2017-08-29 92 views
-1

我試圖將位於Web服務器上的數據庫連接到機器人,但我不知道如何將數據庫連接到機器人。我想讓機器人運行機器人的SELECT和UPDATE查詢。另一個問題是我不打算使用C語言或Java;我計劃在主控制系統中使用python。如何安全地將SQL數據庫連接到外部客戶端?

我知道: PHP 的VBScript 批 的Python

如果有人知道如何將DB連接到機器人這將是一個很大的幫助。

回答

0

那麼基本上如何連接到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 ***') 
+0

這是你在找什麼? – Pacified

相關問題