python3数据库编程_python3数据库编程(MySQL)-Go语言中文社区

目录:

一、MySQLdb 模块使用流程

(一)安装、验证

1. 安装

pip install mysql-client

2. 验证

运行以下两行代码,无报错即为安装成功。

python

import MySQLdb

3. 文档地址

(二)MySQLdb 模块使用流程

1. 使用python连接数据库

import MySQLdb

对象名 = MySQLdb.connect(

host = "主机IP地址",

port = 端口号,

user = "用户名",

passwd = "密码",

db = "数据库",

charset = '编码类型')

例:

import MySQLdb

def get_conn(self):

try:

self.con = MySQLdb.connect(

# 本机地址 localhost 或 127.0.0.1

host = "localhost",

port = 3306,

user = "root",

passwd = "123456",

db = "news",

charset = 'utf8')

except MySQLdb.Error as e:

print("Error %d: %s" % (e.args[0], e.aegs[1]))

return self.con

2. 创建游标对象

对象名.cursor()

3. 使用游标对象的方法操作数据库

1)执行SQL命令

游标对象名.execute('SQL命令')

2)取得结果集的第一条记录

游标对象名.fetchone()

3)取得结果集的 n 条记录

游标对象名.fetchmany(n)

4)取得结果集的所有记录

游标对象名.fetchall()

4. 提交或回滚

对象名.commit

对象名.rollback()

5. 关闭游标对象

cursor.close()

6. 关闭数据库连接

对象名.close()

例:

# 使用例子前,需在数据库创建,代码如下:

CREATE TABLE 'news'(

'id' INT NOT NULL AUTO_INCREMENT,

'title' VARCHAR(200) NOT NULL,

'image' VARCHAR(300) NULL,'author' VARCHAR(20),

'view_count' INT DEFAULT 0,

'created_at' DATETIME NULL,

'is_valid' SMALLINT DEFAULT 1,

PRIMARY KEY('id'))

DEFAULT CHARSET = 'UTF8';

import MySQLdb

class MysqlSearch(object):

# 初始化启动

def __init__(self):

self.get_conn()

# 获取连接

def get_conn(self):

try:

self.conn = MySQLdb.connect(

# 本机地址 localhost 或 127.0.0.1

host = "localhost",

port = 3306,

user = "root",

passwd = "123456",

db = "news",

charset = 'utf8')

except MySQLdb.Error as e:

print("Error: %s" % e)

def close_conn(self):

try:

if self.conn:

# 关闭连接

self.conn.close()

except MySQLdb.Error as e:

print("Error: %s" % e)

# 获取一条数据

def get_one(self):

# 准备SQL

sql = "SELECT * FROM 'news' WHERE 'types' = %s ORDER BY 'created_at' DESC;"

# 找到cursor

cursor = self.conn.cursor()

# 执行SQL

cursor.execute(sql, ('百家',))

# print(cursor.rowcount)

# 拿到一条结果

rests = cursor.fetchone()

rest = dict(zip([k[0] for k in cursor.description], rests))

# 处理数据

# print(rest)

# print(rest['title'])

# 关闭cursor和关闭数据库连接

cursor.close()

self.close_conn()

return rest

# 获取全部数据

def get_more(self):

# 准备SQL

sql = "SELECT * FROM 'news' WHERE 'types' = %s ORDER BY 'created_at' DESC;"

# 找到cursor

cursor = self.conn.cursor()

# 执行SQL

cursor.execute(sql, ('百家',))

# print(cursor.rowcount)

# 拿到全部结果

rests = cursor.fetchall()

rest = [dict(zip([k[0] for k in cursor.description],row)) for row in rests]

# 处理数据

# print(rest)

# print(rest['title'])

# 关闭cursor和关闭数据库连接

cursor.close()

self.close_conn()

return rest

# 分页查询

def get_more_by_page(self, page, page_size):

# 准备SQL

offset = (page - 1) * page_size

sql = "SELECT * FROM 'news' WHERE 'types' = %s ORDER BY 'created_at' DESC LMIT %s, %s;"

# 找到cursor

cursor = self.conn.cursor()

# 执行SQL

cursor.execute(sql, ('百家', offset, page_size))

# print(cursor.rowcount)

# 拿到全部结果

rest = [dict(zip([k[0] for k in cursor.description],row)) for row in cursor.fetchall()]

# 处理数据

# print(rest)

# print(rest['title'])

# 关闭cursor和关闭数据库连接

cursor.close()

self.close_conn()

return rest

# 增加一条数据

def add_one(self):

try:

# 准备SQL

sql = (

"INSERT INTO 'news'('title', 'image', 'content', 'types', 'is_valid')"

"VALUE(%s, %s, %s, %s, %s);"

)

# 获取链接和cursor

cursor = self.conn.cursor()

# 执行sql

# 提交数据到数据库

cursor.execute(sql, ('标题1', '/static/img/news/01.png', '新闻内容1', '推荐', 1))

# 提交事务

self.conn.commit()

# 关闭cursor和链接

cursor.close()

except:

self.conn.rollback()

self.close_conn()

def main():

obj = MysqlSearch()

# 取一条数据

# rest = obj.get_one()

# print(rest)

# print(rest['title'])

# 取全部数据

# rest = obj.get_more()

# for item in rest:

# print(item)

# print(item['title'])

rest = obj.add_one()

print(rest)

if __name__ == '__main__':

main()

二、pymysql 模块使用流程

python3自带 pymysql 模块。

1. 使用python连接数据库

import pymysql

对象名 = pymysql.connect('主机地址','用户名','密码','库名',charset='utf8')

2. 创建游标对象

对象名.cursor()

3. 使用游标对象的方法操作数据库

1)执行SQL命令

游标对象名.execute('SQL命令')

2)取得结果集的第一条记录

游标对象名.fetchone()

3)取得结果集的 n 条记录

游标对象名.fetchmany(n)

4)取得结果集的所有记录

游标对象名.fetchall()

4. 提交或回滚

对象名.commit

对象名.rollback()

5. 关闭游标对象

cursor.close()

6. 关闭数据库连接

对象名.close()

例1:

import pymysql

# 1.创建数据库连接

db = pymysql.connect('localhost', 'root', '123456', 'MOSHOU', charset='utf8')

# 2.创建游标对象

cursor = db.cursor()

# 3.利用游标对象 curso 的方法来操数据库

cursor.execute('insert into sheng values(100,210000,"四川省");')

# 4.提交到数据库 commit

db.commit()

# 5.关闭游标对象

cursor.close()

# 6.关闭数据库连接

db.close()

例2:

import pymysql

db = pymysql.connect('localhost', 'root', '123456', 'MOSHOU', charset='utf8')

cur = db.cursor()

sql_select = 'select * from city;'

cur.execute(sql_select)

data = cur.fetchone()

print('fetchone的结果为', data)

data2 = cur.fetchmany(2)

print('fetchone2的结果为', data2)

data3 = cur.fetchall()

print('fetchall的结果为:')

for i in data3:

print(i)

db.commit()

cur.close()

db.close()

例3:

import pymysql

db = pymysql.connect('localhost', 'root', '123456', 'db2', charset='utf8')

cur = db.cursor()

try:

cur.execute('update CCB set money=5000 where name="Zhuanqian";')

cur.execute('update ICBC set money=9000 where name="Shouqian";')

#cur.execute('update ICBC ...;')

db.commit()

print('ok')

except Exception as e:

db.rollback()

print('出现错误,已回滚')

cur.close()

db.close()

例4:

# 文件名为MySQLPython.py

from pymysql import *

class mysqlpython:

def __init__(self, host, port, db, user, passwd, charset):

self.host = host

self.port = port

self.db = db

self.user = user

self.passwd = passwd

self.charset = charset

def open(self):

self.conn = connect(host=self.host,

port=self.port, db=self.db, user=self.user,

passwd=self.passwf, charset=self.charset)

self.cursor = self.conn.cursor()

def close(self):

self.cursor.close()

self.conn.close()

def zhixing(self, sql):

self.open()

self.cursor.execute(sql)

self.conn.commit()

self.close()

print('ok')

# 文件名为test.py

from mysqlpython import mysqlpython

# 创建实例化对象

sqlh = mysqlpython('localhost', 3306, 'MOSHOU', 'root', '123456')

sql_update = 'update sheng set id=150 where id=1;'

sqlh.zhixing(sql_update)

三、ORM对象关系映射(数据库框架)

(一)MySQL主要实现

1. SqlObject

2. peewee

3. Django’s ORM

4. SQLAlchemy

(二)SQLAlchemy使用

SQLAlchemy原理图:

34f07fd4213b9cba5198c9cf778d1eac.png

1. 安装和配置

pip install SQLAlchemy

测试:python

>>>import sqlalchemy

>>>sqlalchemy.__version__

注意:无报错则安装成功

2. SQLAlchemy模型

1)常见类型

SQLAlchemy的类型

MySQL相对应的类型

SQLAlchemy说明Integer

int

整型

Float

float

浮点型

Boolean

smallint

布尔型

ForeignKey

foreign key

外键

Date/DtarTime

Date/DtarTime

日期

String

varchar

字符类型

例:

class News(Base):

__tablename__ = 'news'

id = Cloumn()

待续。。。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值