如何使用python程序连接MySQL数据库?
当前回答
首先,从https://dev.mysql.com/downloads/connector/python/安装python-mysql连接器
在Python控制台输入:
pip install mysql-connector-python-rf
import mysql.connector
其他回答
只是对上面的回答做了修改。 简单地运行这个命令来安装mysql for python
sudo yum install MySQL-python
sudo apt-get install MySQL-python
记住!区分大小写。
去图书馆的第一步: 打开终端,执行pip install mysql-python-connector。 安装完成后进入第二步。
导入库的第二步: 打开你的python文件并编写以下代码: 进口mysql.connector
第三步连接服务器: 编写以下代码:
Conn = mysql.connector。连接(主机=您的主机名,如localhost或127.0.0.1, 用户名=您的用户名,如root, 密码=您的密码)
第三步制作光标: 使游标便于我们运行查询。 要使游标使用以下代码: Cursor = conn.cursor()
执行查询: 对于执行查询,您可以执行以下操作: cursor.execute(查询)
如果查询更改了表中的任何内容,则需要在执行查询后添加以下代码: conn.commit ()
从查询中获取值: 如果你想从查询中获取值,那么你可以做以下事情: 游标。execute ('SELECT * FROM table_name') for i in cursor: print(i) #或for i in cursor.fetchall(): print(i)
fetchall()方法逐行返回一个包含您请求的值的元组列表。
关闭连接: 要关闭连接,您应该使用以下代码: conn.close ()
处理例外: 要处理异常,你可以用下面的方法: try: #逻辑通过,mysql.connector.errors.Error: #逻辑通过 使用数据库: 例如,您是一个帐户创建系统,您将数据存储在名为blabla的数据库中,您只需向connect()方法添加一个数据库参数,如
mysql.connector。连接(database =数据库名)
不要删除主机、用户名、密码等其他信息。
SqlAlchemy
SQLAlchemy是Python SQL工具包和对象关系映射器 为应用程序开发人员提供了SQL的全部功能和灵活性。 SQLAlchemy提供了一个完整的著名企业级套件 持久性模式,为高效和高性能而设计 数据库访问,改编成简单的python域语言。
安装
pip install sqlalchemy
原始查询
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker, scoped_session
engine = create_engine("mysql://<user_name>:<password>@<host_name>/<db_name>")
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()
蠕虫方式
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>/<db_name>")
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()
如果你想避免安装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。
对于Python3.6,我找到了两个驱动程序:pymysql和mysqlclient。我测试了它们之间的性能,得到的结果是:mysqlclient更快。
下面是我的测试过程(需要安装python lib profilehooks来分析时间流逝:
select * from FOO;
立即在mysql终端执行: set中有46410行(0.10秒)
pymysql (2 . 4s):
from profilehooks import profile
import pymysql.cursors
import pymysql
connection = pymysql.connect(host='localhost', user='root', db='foo')
c = connection.cursor()
@profile(immediate=True)
def read_by_pymysql():
c.execute("select * from FOO;")
res = c.fetchall()
read_by_pymysql()
下面是pymysql的配置文件:
mysqlclient 0.4s)
from profilehooks import profile
import MySQLdb
connection = MySQLdb.connect(host='localhost', user='root', db='foo')
c = connection.cursor()
@profile(immediate=True)
def read_by_mysqlclient():
c.execute("select * from FOO;")
res = c.fetchall()
read_by_mysqlclient()
下面是mysqlclient的配置文件:
因此,mysqlclient似乎比pymysql快得多
推荐文章
- 证书验证失败:无法获得本地颁发者证书
- 当使用pip3安装包时,“Python中的ssl模块不可用”
- 如何关闭mysql密码验证?
- 无法切换Python与pyenv
- Python if not == vs if !=
- 如何从scikit-learn决策树中提取决策规则?
- 为什么在Mac OS X v10.9 (Mavericks)的终端中apt-get功能不起作用?
- 将旋转的xtick标签与各自的xtick对齐
- 为什么元组可以包含可变项?
- MySQL区分大小写查询
- 如何合并字典的字典?
- 如何创建类属性?
- 不区分大小写的“in”
- 在Python中获取迭代器中的元素个数
- MySQL数据库表中的最大记录数