如何使用python程序连接MySQL数据库?
当前回答
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
其他回答
这里有一种方法,使用MySQLdb,它只支持Python 2:
#!/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()
参考这里
如果你不需要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()
如果你想避免安装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。
尝试使用MySQLdb。MySQLdb只支持Python 2。
有一个如何页面在这里: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连接到MySQL的最佳方法是使用MySQL连接器/ python,因为它是MySQL的官方Oracle驱动程序,用于与python一起工作,并且它可以与python 3和python 2一起工作。
按照下面提到的步骤连接MySQL
使用PIP安装连接器 PIP安装mysql-connector-python
或者您可以从https://dev.mysql.com/downloads/connector/python/下载安装程序
使用mysql connector python的connect()方法连接mysql。将所需的参数传递给connect()方法。即主机、用户名、密码和数据库名。 从connect()方法返回的连接对象创建游标对象以执行SQL查询。 工作完成后关闭连接。
例子:
import mysql.connector
from mysql.connector import Error
try:
conn = mysql.connector.connect(host='hostname',
database='db',
user='root',
password='passcode')
if conn.is_connected():
cursor = conn.cursor()
cursor.execute("select database();")
record = cursor.fetchall()
print ("You're connected to - ", record)
except Error as e :
print ("Print your error msg", e)
finally:
#closing database connection.
if(conn.is_connected()):
cursor.close()
conn.close()
参考资料- https://pynative.com/python-mysql-database-connection/
MySQL连接器Python的重要API
对于DML操作-使用cursor.execute()和cursor.executemany()来运行查询。在此之后,使用connection.commit()将您的更改保存到DB 获取数据—使用cursor.execute()运行查询,使用cursor.fetchall(), cursor.fetchone(), cursor.fetchmany(SIZE)获取数据
推荐文章
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 为什么我得到“'str'对象没有属性'读取'”当尝试使用' json。载入字符串?
- 不区分大小写的列表排序,没有降低结果?
- 排序后的语法(key=lambda:…)
- 在烧瓶中返回HTTP状态代码201
- 使用python创建一个简单的XML文件
- APT命令行界面式的yes/no输入?
- 如何打印出状态栏和百分比?
- 在Python中获取大文件的MD5哈希值
- 在Python格式字符串中%s是什么意思?
- 如何循环通过所有但最后一项的列表?
- 如何通过查询在MySQL中获得数据库结构?
- python用什么方法避免默认参数为空列表?
- ValueError: numpy。Ndarray大小改变,可能表示二进制不兼容。期望从C头得到88,从PyObject得到80
- Anaconda /conda -安装特定的软件包版本