python mysql
我如何連接到Python中的MySQL數據庫? (10)
如果你想避免安裝mysql頭文件只是為了從python訪問mysql,停止使用MySQLDb。
使用pymysql 。 它完成了MySQLDb所做的所有工作,但它完全是在Python中實現的, 沒有外部依賴關係 。 這使得所有操作系統上的安裝過程始終如一且簡單。 pymysql
是替代MySQLDb和恕我直言的下降沒有理由曾經使用MySQLDb的任何東西......永遠! - PTSD from installing MySQLDb on Mac OSX and *Nix systems
,但這只是我。
安裝
pip install 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, ('[email protected]', '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, ('[email protected]',))
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。
如何使用python程序連接到MySQL數據庫?
SQLAlchemy的
SQLAlchemy是Python SQL工具包和對象關係映射器,為應用程序開發人員提供了SQL的全部功能和靈活性。 SQLAlchemy提供了一整套眾所周知的企業級持久性模式,專為高效且高性能的數據庫訪問而設計,適用於簡單的Pythonic域語言。
安裝
pip install sqlalchemy
使用RAW查詢
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
engine = create_engine("mysql://<user_name>:<password>@<host_name>/smsmagic")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)
# insert into database
session.execute("insert into person values(2, 'random_name')")
session.flush()
session.commit()
使用ORM方式
from sqlalchemy import Column, Integer, String
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
Base = declarative_base()
engine = create_engine("mysql://<user_name>:<password>@<host_name>/smsmagic")
session_obj = sessionmaker(bind=engine)
session = scoped_session(session_obj)
# Bind the engine to the metadata of the Base class so that the
# declaratives can be accessed through a DBSession instance
Base.metadata.bind = engine
class Person(Base):
__tablename__ = 'person'
# Here we define columns for the table person
# Notice that each column is also a normal Python instance attribute.
id = Column(Integer, primary_key=True)
name = Column(String(250), nullable=False)
# insert into database
person_obj = Person(id=12, name="name")
session.add(person_obj)
session.flush()
session.commit()
Oracle(MySQL)現在支持純Python連接器。 這意味著無需安裝二進製文件:它只是一個Python庫。 它被稱為“連接器/ Python”。
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())
也看看風暴 。 這是一個簡單的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:[email protected]: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
欲了解更多信息,請參閱tutorial 。
作為db驅動程序,還有oursql 。 鏈接中列出的一些原因,這就是為什麼ourql更好:
- oursql具有真正的參數化,將SQL和數據完全分開發送到MySQL。
- oursql允許將文本或二進制數據流式傳輸到數據庫中,並流出數據庫,而不需要在客戶端中緩衝所有內容。
- oursql既可以插入行,也可以懶散地讀取行。
- oursql默認支持unicode。
- oursql支持python 2.4到2.7,在2.6+以上沒有任何棄用警告(請參閱PEP 218),並且2.7沒有完全失敗(請參閱PEP 328)。
- oursql在python 3.x上本地運行。
那麼如何使用oursql連接到mysql?
非常類似於mysqldb:
import oursql
db_connection = oursql.connect(host='127.0.0.1',user='foo',passwd='foobar',db='db_name')
cur=db_connection.cursor()
cur.execute("SELECT * FROM `tbl_name`")
for row in cur.fetchall():
print row[0]
當然對於ORM,SQLAlchemy是一個很好的選擇,正如其他答案中已經提到的那樣。
只是在上面的答案修改。 只需運行此命令即可為python安裝mysql
sudo yum install MySQL-python
sudo apt-get install MySQL-python
記得! 它是區分大小寫的。
嘗試使用MySQLdb
有一個如何在這裡頁面: http://www.kitebird.com/articles/pydbapi.html : http://www.kitebird.com/articles/pydbapi.html
來自頁面:
# server_version.py - retrieve and display database server version
import MySQLdb
conn = MySQLdb.connect (host = "localhost",
user = "testuser",
passwd = "testpass",
db = "test")
cursor = conn.cursor ()
cursor.execute ("SELECT VERSION()")
row = cursor.fetchone ()
print "server version:", row[0]
cursor.close ()
conn.close ()
對於Python 3.3
CyMySQL https://github.com/nakagami/CyMySQL
我在Windows 7上安裝了pip,只需安裝cymysql
(你不需要cython)快速和無痛
這是一種方法:
#!/usr/bin/python
import MySQLdb
# Connect
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
# Execute SQL select statement
cursor.execute("SELECT * FROM location")
# Commit your changes if writing
# In this case, we are only reading data
# db.commit()
# Get the number of rows in the resultset
numrows = cursor.rowcount
# Get and display one row at a time
for x in range(0, numrows):
row = cursor.fetchone()
print row[0], "-->", row[1]
# Close the connection
db.close()