如何使用python程序连接MySQL数据库?
当前回答
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数据库和创建表。想要了解更多,请点击这里。
其他回答
首先,从https://dev.mysql.com/downloads/connector/python/安装python-mysql连接器
在Python控制台输入:
pip install mysql-connector-python-rf
import mysql.connector
如果你想避免安装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。
只是对上面的回答做了修改。 简单地运行这个命令来安装mysql for python
sudo yum install MySQL-python
sudo apt-get install MySQL-python
记住!区分大小写。
你可以用这种方式连接你的python代码到mysql。
import MySQLdb
db = MySQLdb.connect(host="localhost",
user="appuser",
passwd="",
db="onco")
cursor = db.cursor()
这里有一种方法,使用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 -安装特定的软件包版本