如何使用python程序连接MySQL数据库?


当前回答

如果你想避免安装mysql头文件只是为了从python访问mysql,请停止使用MySQLDb。

使用pymysql。它做了MySQLDb做的所有事情,但是它完全是用Python实现的,没有外部依赖。这使得在所有操作系统上的安装过程一致且简单。pymysql是MySQLDb的替代品,在我看来,没有任何理由使用MySQLDb做任何事情…!-在Mac OSX和*Nix系统上安装MySQLDb的PTSD,但这只是我的想法。

安装

安装pymysql

就是这样……你已经准备好了。

来自pymysql Github repo的示例用法

import pymysql.cursors
import pymysql

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

在现有代码中快速透明地替换MySQLdb

如果你有使用MySQLdb的现有代码,你可以通过以下简单的过程轻松地将其替换为pymysql:

# import MySQLdb << Remove this line and replace with:
import pymysql
pymysql.install_as_MySQLdb()

所有对MySQLdb的后续引用都将透明地使用pymysql。

其他回答

Mysqlclient是最好的,因为其他的只支持特定版本的python

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

参见https://github.com/PyMySQL/mysqlclient-python

尽管你们中的一些人可能会把我的回答标记为重复,并对我抄袭别人的回答感到不安,但我真的想强调Napik先生回答的一个方面。因为我错过了这个,我导致了全国范围内的网站停机(9分钟)。如果有人分享这个信息,我就可以阻止它了!

下面是他的代码:

import mysql.connector    
cnx = mysql.connector.connect(user='scott', password='tiger',
                              host='127.0.0.1',
                              database='employees')
try:
   cursor = cnx.cursor()
   cursor.execute("""select 3 from your_table""")
   result = cursor.fetchall()
   print(result)
finally:
    cnx.close()

这里重要的是Try and Finally子句。这允许始终关闭连接,不管代码的游标/sqlstatement部分发生了什么。大量的活动连接会导致DBLoadNoCPU峰值,并可能导致db服务器崩溃。

我希望这个警告有助于节省服务器和最终的工作!: D

在终端上执行以下命令安装mysql connector:

pip install mysql-connector-python

在你的python编辑器中运行这个来连接MySQL:

import mysql.connector

mydb = mysql.connector.connect(
      host="localhost",
      user="username",
      passwd="password",
      database="database_name"
)

执行MySQL命令的示例(在python编辑器中):

mycursor = mydb.cursor()
mycursor.execute("CREATE TABLE customers (name VARCHAR(255), address VARCHAR(255))")    
mycursor.execute("SHOW TABLES")

mycursor.execute("INSERT INTO customers (name, address) VALUES ('John', 'Highway 21')")    
mydb.commit() # Use this command after insert, update, delete commands

更多命令:https://www.w3schools.com/python/python_mysql_getstarted.asp

PyMySQL 0.10.1 -发布:2020年9月10日,也支持python3。

python3 -m pip install PyMySQL

简单的代码:

import pymysql

# Connect to the database
conn = pymysql.connect(host='127.0.0.1',user='root',passwd='root',db='fax')

# Create a Cursor object
cur = conn.cursor()

# Execute the query
cur.execute("SELECT * FROM fax.student")

# Read and print records
for row in cur.fetchall():
    print(row)

输出:

(1, 'Petar', 'Petrovic', 1813, 'Njegusi')
(2, 'Donald', 'Tramp', 1946, 'New York')
(3, 'Bill', 'Gates', 1955, 'Seattle')

首先安装驱动程序

pip install MySQL-python   

然后一个基本代码是这样的:

#!/usr/bin/python
import MySQLdb

try:
    db = MySQLdb.connect(host="localhost",      # db server, can be a remote one 
                     db="mydb"                  # database
                     user="mydb",               # username
                     passwd="mydb123",          # password for this username
                     )        

    # Create a Cursor object
    cur = db.cursor()

    # Create a query string. It can contain variables
    query_string = "SELECT * FROM MY_TABLE"

    # Execute the query
    cur.execute(query_string)

    # Get all the rows present the database
    for each_row in cur.fetchall():
        print each_row

    # Close the connection
    db.close()
except Exception, e:
    print 'Error ', e