1、MySQLdb
# 前置条件
sudo apt-get install python-dev libmysqlclient-dev # Ubuntu
sudo yum install python-devel mysql-devel # Red Hat / CentOS
# 安装
pip install MySQL-python
Windows 直接通过下载 exe 文件安装
#!/usr/bin/python
import MySQLdb
db = MySQLdb.connect(
host = "localhost", # 主机名
user = "root", # 用户名
passwd = "pythontab.com", # 密码
db = "testdb") # 数据库名称
# 查询前,必须先获取游标
cur = db.cursor()
# 执行的都是原生SQL语句
cur.execute("SELECT * FROM mytable")
for row in cur.fetchall():
print(row[0])
db.close()
2、mysqlclient
# Windows安装
pip install some-package.whl
# linux 前置条件
sudo apt-get install python3-dev # debian / Ubuntu
sudo yum install python3-devel # Red Hat / CentOS
brew install mysql-connector-c # macOS (Homebrew)
pip install mysqlclient
3、PyMySQL
pip install PyMySQL
# 为了兼容mysqldb,只需要加入
pymysql.install_as_MySQLdb()
import pymysql
conn = pymysql.connect(host = '127.0.0.1', user = 'root', passwd = "pythontab.com", db = 'testdb')
cur = conn.cursor()
cur.execute("SELECT Host,User FROM user")
for r in cur:
print(r)
cur.close()
conn.close()
4、peewee
pip install peewee
import peewee
from peewee import *
db = MySQLDatabase('testdb', user = 'root', passwd = 'pythontab.com')
class Book(peewee.Model):
author = peewee.CharField()
title = peewee.TextField()
class Meta:
database = db
Book.create_table()
book = Book(author = "pythontab", title = 'pythontab is good website')
book.save()
for book in Book.filter(author = "pythontab"):
print(book.title)
5、SQLAlchemy
from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker
from sqlalchemy_declarative import Address, Base, Person
class Address(Base):
__tablename__ = 'address'
id = Column(Integer, primary_key = True)
street_name = Column(String(250))
engine = create_engine('sqlite:///sqlalchemy_example.db')
Base.metadata.bind = engine
DBSession = sessionmaker(bind = engine)
session = DBSession()
# Insert a Person in the person table
new_person = Person(name = 'new person')
session.add(new_person)
session.commit()
MySQLdb.connect是python 连接MySQL数据库的方法,在Python中 import MySQLdb即可使用,至于connect中的参数很简单:\x0d\x0ahost:MySQL服务器名\x0d\x0auser:数据库使用者\x0d\x0apassword:用户登录密码\x0d\x0adb: *** 作的数据库名\x0d\x0acharset:使用的字符集(一般是gb2312)\x0d\x0acursor = db.cursor() 其实就是用来获得python执行Mysql命令的方法,也就是\x0d\x0a我们所说的 *** 作游标\x0d\x0a下面cursor.execute则是真正执行MySQL语句,即查询TABLE_PARAMS表的数据。\x0d\x0a至于fetchall()则是接收全部的返回结果行 row就是在python中定义的一个变量,用来接收返回结果行的每行数据。同样后面的r也是一个变量,用来接收row中的每个字符,如果写成C的形式就更好理解了\x0d\x0afor(string row = ''row 回答于 2022-11-16
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)