【问题标题】:best way for python to interface with MySQLpython与MySQL交互的最佳方式
【发布时间】:2016-06-09 02:07:42
【问题描述】:

我对编程还是很陌生,并试图自学正确的做事方式。

我目前正在编写一个脚本,该脚本将在 python 中每秒生成 1-3 个值,然后将其保存到 MySQL 数据库中。接下来将构建一个 Web 界面,该界面将采用这些值并很好地显示它们,但现在我只想保存数据。

我将在 Raspberry Pi 上运行 Python 代码,并希望在带有 MySQL 服务器的 Web 服务器上运行。如果不在另一个 Raspberry Pi 上的该设备上。

我在这里要问的是,Python 与 MySQL 一起工作的最佳方式是什么?库或 HTTP GET,或者我不知道的另一种方式... 因为,我要构建一个 Web 界面,所以我正在考虑创建一个 API.php 页面来接受 GET 请求,然后 PHP 代码将编写数据到 MySQL 数据库。

我的想法是让 Python 生成一个链接,然后使用请求库来请求站点,例如 http://127.0.0.1/API.php?value1=XXX&Value2=YYY&value3=ZZZ,然后如果数据保存正确,则等待 JSON 返回类似“已保存数据”的内容。然后继续生成下一个值的循环。

这是解决此问题的最佳方法还是有更好的方法?我知道我会遇到一些安全问题,我希望在我了解更多有关编码的信息后解决这些问题。请记住,我希望每 1 或 5 秒写入一次数据。希望,每 1 秒。

谢谢大家的回复, 索隆

【问题讨论】:

  • 您正在寻找与 MySQL 的 Python 绑定。

标签: python mysql json http get


【解决方案1】:

您有很多方法可以做到这一点,但是由于您声明 MySQL 服务器可以在同一个树莓派上或在不同的树莓派上,因此以下是获得所需设置的最简单方法。

首先,您需要安装一个包含 MySQL 绑定的 Python 包。那里有很多,但MySQL-python 似乎已经成熟且足够好。

要安装它:

$ pip install mysql

(如果您还不熟悉pip,请查看pip documentation 以开始使用。)

在您的一个 Raspberry Pi 上运行 MySQL 服务器后,下面是一个示例,您需要在代码中执行哪些操作以连接到服务器并运行各种类型的查询:

import MySQLdb

host = '192.168.99.100'
user = 'myuser'
password = 'secret'
port = 3306
db = 'test'

conn = MySQLdb.Connection(
    host=host,
    user=user,
    passwd=password,
    port=port,
    db=db
)

# Example of how to insert new values:
conn.query("""INSERT INTO mytable VALUES ('foo3', 'bar2')""")
conn.commit()

# Example of how to fetch table data:
conn.query("""SELECT * FROM mytable""")
result = conn.store_result()
for i in range(result.num_rows()):
    print(result.fetch_row())

查看MySQL-python user docs 了解有关如何使用该库的更多详细信息。

上面的代码假设了一些关于你的 MySQL 服务器的事情:

  • 您的服务器在192.168.99.100 运行。它可以是 127.0.0.1 (localhost) 或其他地址。
  • 您的服务器已经定义了用户myuser,并具有密码和适当的权限。
  • 您已经创建了一个名为 test 的数据库。
  • 您已经在数据库test 上创建了一个名为mytable 的表,其中包含foo 和bar 的VARCHAR 字段。

我不会详细介绍这些细节,因为这超出了本主题的范围,但如果您需要帮助,请查看creating users 和 creating tables 的 MySQL 文档。

【讨论】:

  • sudo pip install mysql 在 MacOS Sierra 上失败,EnvironmentError: mysql_config not found。
  • @EricFossum 有什么问题?
  • ``` ➜ ~ python3 -m pip install mysql 正在收集 mysql ... 正在收集 MySQL-python(来自 mysql)... 命令 python setup.py egg_info 的完整输出:Traceback(最近一次调用最后):文件“”,第 1 行,在 文件“/tmp/pip-build-r33d2gw7/MySQL-python/setup.py”,第 13 行,在 from setup_posix import get_config File“ /tmp/pip-build-r33d2gw7/MySQL-python/setup_posix.py",第 2 行,在 from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' ``` 我删除了一些绒毛
  • @EricFossum 看起来像是库中的一个错误。我刚刚提交了一个补丁:github.com/farcepest/MySQLdb1/pull/136.
【解决方案2】:

首先安装 mysqlclient,因为这也将为您提供使用 Python 3.6 的支持

pip install mysqlclient

示例代码

    import mysql.connector
    import _mysql
    db=_mysql.connect("127.0.0.1","root","umer","sys")
    #db=_mysql.connect(host,user,password,db)
    # Example of how to insert new values:
    db.query("""INSERT INTO table1 VALUES ('01', 'myname')""")
    db.store_result()
    db.query("SELECT * FROM new1.table1 ;") 
    #new1 is scheme table1 is table mysql 
    res= db.store_result()
    for i in range(res.num_rows()):
        print(result.fetch_row())

【讨论】:

  • 不起作用 - sh: mysql_config: command not found 运行时 pip install mysql
【解决方案3】:

Python 用 pymysql 连接 xampp mysql windows:

第一步:

运行命令提示符 D:\python-3.6.2\Scripts> pip install pymysql

第二步:

#!D:/python-3.6.2/python.exe 
print ("Content-Type: text/html\n")
import pymysql
conn = pymysql.connect(host='localhost', port=3306, user='root', passwd='', db='python_mysql')
cur = conn.cursor()
cur.execute("SELECT * FROM authors")
print(cur.description)
print(" Test")
for row in cur:
    print(row)
cur.close()
conn.close()

在 htdocs/PythonProject 中将文件另存为 testconn.py 并打开 http://localhost/PythonProject\testconn.py

Crud Python 和 MySQL:

https://github.com/matinict/python-in-xampp-for-windows/

【讨论】:

    【解决方案4】:

    pip install mysql 在 MacOS Sierra 上对我来说失败了,EnvironmentError: mysql_config not found。

    pip install pymysql 有效。 PyMySQL 是用纯 Python 编写的,因此应该比静态编译的模块更具跨平台性。

    示例代码:

    import pymysql.cursors
    
    # Connect to the database
    connection = pymysql.connect(host='localhost',
                                 user='user',
                                 password='passwd',
                                 db='db',
                                 charset='utf8mb4',
                                 cursorclass=pymysql.cursors.DictCursor)
    
    try:
        with connection.cursor() as cursor:
            # Create a new record
            sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
            cursor.execute(sql, ('webmaster@python.org', 'very-secret'))
    
        # connection is not autocommit by default. So you must commit to save
        # your changes.
        connection.commit()
    
        with connection.cursor() as cursor:
            # Read a single record
            sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
            cursor.execute(sql, ('webmaster@python.org',))
            result = cursor.fetchone()
            print(result)
    finally:
        connection.close()
    

    【讨论】:

    • 我也在 Sierra 但目前不能使用:如果有人可以提供帮助,这是我的问题:stackoverflow.com/questions/46145845/…
    • 不会与 pymysql 一起用于严肃的项目......维护者没有解决任何错误,他只是要求你去堆栈溢出,对于显然在库中的错误。我的意思是我理解人们很忙,花很长时间来解决错误是可以的。但说错误是“罕见的”不是。
    【解决方案5】:
    import mysql.connector as connector
    
    
    class DbHelper:
        def __init__(self):
            self.conn = connector.connect(host = '127.0.0.1', user = 'root', password = '', database = 'python_test')
    ##        print("Database connected...")
    
            query = 'create table if not exists user(userID int primary key, firstname varchar(200),lastname varchar(200), Dob varchar(15), contact varchar(10), address varchar(100))'
            curr = self.conn.cursor()
            curr.execute(query)
    ##        print("Table Created")
            print()
    
    
        def insert_Data(self, userID, firstname, lastname, Dob, contact, address):
    
            query = "insert into user (userID, firstname, lastname, Dob, contact, address) values({},'{}','{}','{}','{}','{}')".format(userID,firstname, lastname, Dob, contact, address)
                
            curr = self.conn.cursor()
            curr.execute(query)
            self.conn.commit()
            print(query)
            print("User data inserted....")
    
        def display_Data(self):
            query = 'select * from user'
    ##        print("query: ", query)
            print()
    
            curr = self.conn.cursor()
            curr.execute(query)
    
            for row in curr:
                print('userID :', row[0])
                print('firstname :', row[1])
                print('lastname :', row[2])
                print('Dob :', row[3])
                print('contact :', row[4])
                print('address :', row[5])
                print()
                print()
                
    ##        print(" All user data....")
            
    
        def delete_user(self, userID):
    
            query = "DELETE FROM user WHERE userID={}".format(userID)
            curr = self.conn.cursor()
            curr.execute(query)
            self.conn.commit()
    ##        print(query)
            print("Data delete for UserID " +str(userID))
    
        def update_Data(self, userID, newfirstname, newlastname, newDob, newcontact, newaddress):
    
            query = "update user set firstname = '{}', lastname ='{}', Dob = '{}', contact = '{}', address = '{}' where userID = {}".format(newfirstname, newlastname, newDob, newcontact, newaddress,userID)
            curr = self.conn.cursor()
            curr.execute(query)
            self.conn.commit()
    ##        print(query)
            print()
            print("Data updated for UserID " +str(userID))
               
            
    
    ##db = DbHelper()
    ##db.update_Data(1,'saurabh','sharma','25-06-1998','9892809732','malad')
    

    【讨论】:

    • 你能花时间把这个答案注释为python语言吗?在反引号中插入代码
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-19
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    相关资源
    最近更新 更多