数据库开发
比较有名的模块有:
MySQLdb 支持Python2,不知道Python3,已停止更新
mysqlclient 在MySQLdb的基础上支持Python3
MYSQL官方Connector 网址:https://dev.mysql.com/downloads/
pymysql 语法兼容MySQLdb,使用纯Python写的Mysql客户端库,支持Python3
pymysql与MySQLdb模块
MySQLdb的安装命令是:pip install mysqlclient
import pymysql
import MySQLdb
conn = None
cursor = None
try:
# conn = pymysql.connect(host='localhost', user='user', password='password', database='test', port=3306) # 用pymysql建立mysql连接
conn = MySQLdb.connect(host='localhost', user='user', password='password', database='db_test', port=3306) # 用MySQLdb建立mysql连接
print(type(conn), conn)
conn.ping(False) # ping不通抛异常,True则重连
# with conn as cursor: # pymysql支持上下文获得游标
cursor = conn.cursor() # 获得游标
sql = """select * from tb_test"""
rows = cursor.execute(sql) # 执行sql语句
print(rows) # 返回行数
print('1', cursor.rownumber, cursor.rowcount) # 游标当前行数,总行数
print(cursor.fetchone()) # 返回一行
print('2', cursor.rownumber, cursor.rowcount)
print(cursor.fetchmany(2)) # 返回指定若干行
print('3', cursor.rownumber, cursor.rowcount)
cursor.rownumber = 0 # 设置游标行数,支持正负数
print(cursor.fetchall()) # 返回游标后的所有行
print('4', cursor.rownumber, cursor.rowcount)
conn.commit() # 进行增删改时,需要提交事务,查不用
except:
conn.rollback() # 事务回滚
finally:
if cursor:
cursor.close() # 关闭游标
if conn:
conn.close() # 关闭数据库连接
元编程
写代码来生成需要的代码,这就是元编程
类构建
class Test(object):
a = 1
def __init__(self, b):
self.b = b
def init(self, b):
self.b = b
test = type('test', (object,), {'__init__': init})
test.a = 1
print(type(Test), Test, Test.mro(), Test.__dict__)
print(type(test), test, test.mro(), Test.__dict__)
t1 = Test(3)
t2 = test(3)
print(t1.a)
print(t2.a)
print(type(t1), t1, t1.__dict__)
print(type(t2), t2, t2.__dict__)
# test与Test结构一样
构建元类
class A(type): # 元类
def __new__(cls, name, bases, dicts):
print(cls)
print(name)
print(bases)
print(dicts)
return super().__new__(cls, name, bases, dicts)
class B(A): # 继承父类
pass
class C(metaclass=A): # 使用元类A
pass
class D(C): # 继承父类C,使用元类A
pass
E = A('E', (C,), {})
print(type(A), A.__bases__) # <class 'type'> (<class 'type'>,)
print(type(B), B.__bases__) # <class 'type'> (<class '__main__.A'>,)
print(type(C), C.__bases__, C.mro()) # <class '__main__.A'> (<class 'object'>,)
print(type(D), D.__bases__, D.mro()) # <class '__main__.A'> (<class '__main__.C'>,)
print(type(E), E.__bases__, E.mro()) # <class '__main__.A'> (<class '__main__.C'>,)