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


当前回答

首先安装驱动程序

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 

其他回答

首先,从https://dev.mysql.com/downloads/connector/python/安装python-mysql连接器

在Python控制台输入:

pip install mysql-connector-python-rf
import mysql.connector

再来看看Storm。它是一个简单的SQL映射工具,允许您轻松地编辑和创建SQL条目,而无需编写查询。

这里有一个简单的例子:

from storm.locals import *

# User will be the mapped object; you have to create the table before mapping it
class User(object):
        __storm_table__ = "user" # table name
        ID = Int(primary=True) #field ID
        name= Unicode() # field name

database = create_database("mysql://root:password@localhost:3306/databaseName")
store = Store(database)

user = User()
user.name = u"Mark"

print str(user.ID) # None

store.add(user)  
store.flush() # ID is AUTO_INCREMENT

print str(user.ID) # 1 (ID)

store.commit() # commit all changes to the database

查找和使用对象:

michael = store.find(User, User.name == u"Michael").one()
print str(user.ID) # 10

用主键查找:

print store.get(User, 1).name #Mark

有关更多信息,请参阅教程。

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

在终端上执行以下命令安装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

如果你不需要MySQLdb,但愿意接受任何库,我非常非常推荐MySQL连接器/Python从MySQL: http://dev.mysql.com/downloads/connector/python/。

它是一个包(大约110k),纯Python,所以它与系统无关,安装非常简单。你只需要下载,双击,确认许可协议就可以了。不需要Xcode, MacPorts,编译,重新启动…

然后你可以这样联系:

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