2017-08-29 5 views
-1

Webサーバー上にあるデータベースをロボットに接続しようとしていますが、データベースをロボットに接続する方法がわかりません。私はロボットがSELECTとUPDATEクエリをロボットから実行するようにしたいと思います。もう1つの問題は、C言語やJavaの使用を意図していないことです。私はメインコントロールシステムでpythonを使うことを計画しています。SQLデータベースを外部クライアントに安全に接続するにはどうすればよいですか?

私は知っていますか: PHP VBScriptの バッチ Pythonの

誰もが、それは大きな助けになりボットにDBを接続する方法を知っていれば。

答えて

0

だから基本的にどのようにPythonでSQL DBに接続するには?私は今、同じことをやっている仮想ボットに取り組んでいます。モジュール、SQLコネクターを見てください!
http://www.mysqltutorial.org/python-connecting-mysql-databases/
あなたは

[mysql] 
host = localhost 
database = python_mysql 
user = root 
password = 

読むconfig.iniの資格情報との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

関連する問題