如何使用python程序连接MySQL数据库?
当前回答
从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)获取数据
其他回答
Python没有内置的库来与MySQL交互,所以为了在MySQL数据库和Python之间建立连接,我们需要为我们的Python环境安装MySQL驱动程序或模块。
pip install mysql-connector-python
MySQL - connector - Python是一个开源的Python库,可以用几行代码将你的Python代码连接到MySQL数据库。而且它与最新版本的Python非常兼容。
安装MySQL -connector-python后,可以使用下面的代码片段连接到MySQL数据库。
import mysql.connector
Hostname = "localhost"
Username = "root"
Password ="admin" #enter your MySQL password
#set connection
set_db_conn = mysql.connector.connect(host= Hostname, user=Username, password=Password)
if set_db_conn:
print("The Connection between has been set and the Connection ID is:")
#show connection id
print(set_db_conn.connection_id)
连接Django和MySQL
在Django中,要将你的模型或项目连接到MySQL数据库,你需要安装mysqlclient库。
pip install mysqlclient
为了配置你的Django设置,让你的项目可以连接到MySQL数据库,你可以使用下面的设置。
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'database_name',
'USER': 'username',
'PASSWORD': 'databasepassword@123',
'HOST': 'localhost', # Or an IP Address that your DB is hosted on
'PORT': '3306',
}
我在我的博客上写了一个专门的Python教程,介绍了如何使用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
对于较新版本的Python (>=3.6)
使用mysqlclient或pymysql(推荐)。
对于较旧版本的Python (<3.7, 2.4 <= Python <= 2.7)
如果您正在使用较旧版本的Python(不幸的是),那么您也可以尝试-> oursql。
但是请注意,该项目不再维护,错误修复也不会推送。
作为一个db驱动程序,还有oursql。这个链接列出了一些原因,说明了为什么oursql更好:
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上本机运行。
那么如何连接mysql与oursql?
与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是一个很好的选择,正如已经在其他答案中提到的那样。
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')
这里有一种方法,使用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()
参考这里
推荐文章
- 将表从一个数据库复制到另一个数据库的最简单方法?
- 为什么我得到“'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 -安装特定的软件包版本