如何使用python程序连接MySQL数据库?
当前回答
首先,从https://dev.mysql.com/downloads/connector/python/安装python-mysql连接器
在Python控制台输入:
pip install mysql-connector-python-rf
import mysql.connector
其他回答
在终端上执行以下命令安装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
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数据库和创建表。想要了解更多,请点击这里。
MySQLdb是最直接的方法。您可以在连接上执行SQL查询。时期。
我更喜欢使用强大的SQLAlchemy,这也是python化的。下面是一个与查询相关的教程,下面是一个关于SQLALchemy的ORM功能的教程。
用Python 2分三步连接到MYSQL
1 -设置
在做任何事情之前,都必须安装MySQL驱动程序。与PHP不同,Python默认只安装SQLite驱动程序。最常用的包是MySQLdb,但是使用easy_install很难安装它。请注意MySQLdb只支持Python 2。
Windows用户可获取MySQLdb的exe文件。
对于Linux,这是一个临时包(python-mysqldb)。(您可以使用sudo apt-get install python-mysqldb(适用于基于debian的发行版),yum install MySQL-python(适用于基于rpm的发行版)或dnf install python-mysql(适用于现代fedora发行版)在命令行下载。)
对于Mac,可以使用Macport安装MySQLdb。
2 -用法
安装完成后,重新启动。这不是强制性的,但如果出现问题,它会阻止我回答这篇文章中的3或4个其他问题。所以请重新启动。
然后它就像使用任何其他包一样:
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
user="john", # your username
passwd="megajonhy", # your password
db="jonhydb") # name of the data base
# you must create a Cursor object. It will let
# you execute all the queries you need
cur = db.cursor()
# Use all the SQL you like
cur.execute("SELECT * FROM YOUR_TABLE_NAME")
# print all the first cell of all the rows
for row in cur.fetchall():
print row[0]
db.close()
当然,有成千上万种可能性和选择;这是一个非常基本的例子。你得看一下文件。这是一个很好的起点。
3 -更高级的使用
一旦你知道了它是如何工作的,你可能想要使用ORM来避免手动编写SQL,并像操作Python对象一样操作你的表。Python社区中最著名的ORM是SQLAlchemy。
我强烈建议你使用它:你的生活将会变得更容易。
我最近发现了Python世界中的另一颗宝石:peewee。这是一个非常精简的ORM,非常容易和快速设置然后使用。它使我的一天小项目或独立的应用程序,使用大工具,如SQLAlchemy或Django是多余的:
import peewee
from peewee import *
db = MySQLDatabase('jonhydb', user='john', passwd='megajonhy')
class Book(peewee.Model):
author = peewee.CharField()
title = peewee.TextField()
class Meta:
database = db
Book.create_table()
book = Book(author="me", title='Peewee is cool')
book.save()
for book in Book.filter(author="me"):
print book.title
这个例子是开箱即用的。只需要使用peewee (pip install peewee)即可。
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')
推荐文章
- Pandas:索引数据帧时的多个条件-意外行为
- 如何更改Django应用程序的名称?
- 如何在python抽象类中创建抽象属性?
- 用MySQL LEFT JOIN删除行
- MySQL - length() vs char_length()
- “克隆”行或列向量
- 在python shell中按方向键时看到转义字符
- 使用PDO进行行计数
- 在pip install中方括号是什么意思?
- 在Mac上安装MySQL后,使用ALTER USER语句重置MySQL root密码
- 使用Matplotlib以非阻塞的方式绘图
- 使用sklearn缩放Pandas数据框架列
- 如何创建关键或附加一个元素的关键?
- my.cnf文件在macOS上的位置
- virtualenv的问题-无法激活