Python与MySQL交互的最佳方式是什么?

11

我对编程还很陌生,正在尝试自学正确的做法。

我目前正在编写一个脚本,将Python每秒生成的1-3个数值保存到MySQL数据库中。未来会构建一个Web界面,以美观的方式显示这些值,但现在我只想保存数据。

我将在Raspberry Pi上运行Python代码,并希望在Web服务器上运行MySQL服务器。如果不是在该设备上,就在另一个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秒。

谢谢大家的回复, Throdne


1
你正在寻找一个Python与MySQL的绑定 - Jonathon Reinhart
5个回答

10

有很多方法可以做到这一点,但由于你提到MySQL服务器可能在同一个树莓派上或另一个树莓派上,以下是设置所需内容的最简单方法。

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

安装方式如下:

$ pip install mysql

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

一旦您在树莓派中的一个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用户文档,了解如何使用该库的更多细节。

上述代码假设您的MySQL服务器有以下几点:

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

我不会进入这些细节,因为这略微超出了本主题的范围,但如果您需要帮助,请查看MySQL文档以了解创建用户创建表格的方法。


在MacOS Sierra上执行sudo pip install mysql会失败,并显示EnvironmentError: mysql_config not found - Cees Timmerman
@EricFossum 有什么问题吗? - larsbutler
➜ ~ python3 -m pip install mysql 正在收集 mysql ... 正在收集 MySQL-python (from mysql) ... 完整输出如下: Traceback (most recent call last): File "<string>", line 1, in <module> File "/tmp/pip-build-r33d2gw7/MySQL-python/setup.py", line 13, in <module> from setup_posix import get_config File "/tmp/pip-build-r33d2gw7/MySQL-python/setup_posix.py", line 2, in <module> from ConfigParser import SafeConfigParser ModuleNotFoundError: No module named 'ConfigParser' - Eric Fossum
1
@EricFossum 看起来是库中的一个错误。我刚刚提交了一个补丁:https://github.com/farcepest/MySQLdb1/pull/136。 - larsbutler
1
这可能不应该成为2022年的最佳答案,因为这个软件包已经8年没有更新了。https://github.com/farcepest/MySQLdb1 - Michael Altfield

4

首先安装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())

运行 pip install mysql 时出现 sh: mysql_config: command not found 的错误。 - Oly Dungey

3

使用pymysql连接xampp mysql windows的Python代码:

步骤1:

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

步骤2:

#!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()

请将文件保存为testconn.py,放在htdocs/PythonProject目录下,并打开http://localhost/PythonProject\testconn.py。

使用Python和MySQL进行CRUD操作:

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


3

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上,但目前无法使用任何一个:如果有人可以帮忙,这是我的问题: https://stackoverflow.com/questions/46145845/cannot-make-remote-connection-with-pymysql-pymysql-err-internalerror-packet-se - ballade4op52
1
严肃的项目不应选择pymysql……维护者不解决任何错误,仅建议你去Stack Overflow寻求帮助,即使那些错误明显是库本身的问题。我理解人们很忙,花时间解决错误也是可以接受的,但说这些错误“很少见”就不太妥当了。 - Mohamed Benkedadra

0
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语言吗?请在反引号围栏中插入代码。 - rikyeah

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接