腾讯云服务器可以做网站,网站设计制作步骤,wordpress 电台插件,给传销产品做网站目录
一、数据库操作
1、创建
1-1、用mysql-connector-python库
1-2、用PyMySQL库
1-3、用PeeWee库
1-4、用SQLAlchemy库
2、删除
2-1、用mysql-connector-python库
2-2、用PyMySQL库
2-3、用PeeWee库
2-4、用SQLAlchemy库
二、数据表操作
1、创建
1-1、用mysql-…目录
一、数据库操作
1、创建
1-1、用mysql-connector-python库
1-2、用PyMySQL库
1-3、用PeeWee库
1-4、用SQLAlchemy库
2、删除
2-1、用mysql-connector-python库
2-2、用PyMySQL库
2-3、用PeeWee库
2-4、用SQLAlchemy库
二、数据表操作
1、创建
1-1、用mysql-connector-python库
1-2、用PyMySQL库
1-3、用PeeWee库
1-4、用SQLAlchemy库
2、删除
2-1、用mysql-connector-python库
2-2、用PyMySQL库
2-3、用PeeWee库
2-4、用SQLAlchemy库
三、推荐阅读
1、Python函数之旅
2、Python算法之旅
3、博客个人主页 一、数据库操作
1、创建 现需在MySQL服务器上新建数据库test_database同时在新建的数据test_database中创建数据表test_table。不管是数据库还是数据表若不存在则新建。
1-1、用mysql-connector-python库
import mysql.connector
# 配置数据库连接信息
config {user: root,password: 123456, # 在此输入你的MySQL密码请自行修改host: 127.0.0.1,database: mysql # 如果要指定数据库
}
# 连接到MySQL服务器
try:cnx mysql.connector.connect(**config)cursor cnx.cursor()# 创建新数据库test_database如果不存在create_db_query CREATE DATABASE IF NOT EXISTS test_databasecursor.execute(create_db_query)# 切换到新数据库use_db_query USE test_databasecursor.execute(use_db_query)# 创建新表test_table如果不存在# 假设我们有一个简单的表包含 id整数主键自增、name字符串和 age整数create_table_query CREATE TABLE IF NOT EXISTS test_table ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, age INT ) cursor.execute(create_table_query)# 提交事务cnx.commit()
except mysql.connector.Error as err:print(fError: {err})if cnx.is_connected():cnx.rollback() # 如果需要回滚事务的话
finally:# 关闭游标和连接if cursor:cursor.close()if cnx.is_connected():cnx.close()
1-2、用PyMySQL库
import pymysql
# 配置数据库连接信息
config {user: root,password: 123456, # 在此输入你的MySQL密码请自行修改host: 127.0.0.1,database: mysql # 如果要指定数据库但这里我们稍后会创建新数据库
}
# 连接到MySQL服务器
try:# 注意PyMySQL没有直接使用**config的方式需要分别传入参数cnx pymysql.connect(hostconfig[host],userconfig[user],passwordconfig[password],charsetutf8mb4, # 可选添加字符集支持cursorclasspymysql.cursors.DictCursor) # 使用字典游标# 创建新数据库test_database如果不存在with cnx.cursor() as cursor:create_db_query CREATE DATABASE IF NOT EXISTS test_databasecursor.execute(create_db_query)# 切换到新数据库# 注意PyMySQL没有直接的USE语句我们需要断开连接并重新连接到新数据库cnx.close()config[database] test_databasecnx pymysql.connect(**config, charsetutf8mb4, cursorclasspymysql.cursors.DictCursor)# 创建新表test_table如果不存在# 假设我们有一个简单的表包含 id整数主键自增、name字符串和 age整数with cnx.cursor() as cursor:create_table_query CREATE TABLE IF NOT EXISTS test_table ( id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255) NOT NULL, age INT ) cursor.execute(create_table_query)# 提交事务cnx.commit()
except pymysql.MySQLError as err:print(fError: {err})if cnx:cnx.rollback() # 如果需要回滚事务的话但对于DDL语句通常没有回滚的必要
finally:# 关闭游标和连接if cnx:cnx.close()
1-3、用PeeWee库
from peewee import *
# 配置数据库连接信息这里尝试连接到名为mysql的数据库
db MySQLDatabase(mysql, userroot, password123456, host127.0.0.1)
# 尝试连接数据库
try:db.connect()# 创建新数据库test_database如果不存在这里通过执行原始SQL语句来实现db.execute_sql(CREATE DATABASE IF NOT EXISTS test_database)# 更改数据库连接对象以连接到新创建的数据库或已存在的db MySQLDatabase(test_database, userroot, password123456, host127.0.0.1)db.connect()# 定义模型对应于数据库表class TestTable(Model):id AutoField() # 自增主键name CharField(nullFalse) # 字符字段不能为空age IntegerField(nullTrue) # 整数字段可以为空class Meta:database db # 指定该模型使用的数据库连接# 自定义的创建表方法这里实际上是覆盖了基类Model的create_table方法# 但实际上这里不需要重新定义因为Peewee会自动在调用create_table时处理提交事务def create_table(cls, fail_silentlyFalse, **options):super(TestTable, cls).create_table(fail_silently, **options)db.commit() # 这里提交事务其实是不必要的因为Peewee默认会处理# 调用自定义的create_table方法来创建表如果不存在# 但通常我们会直接调用 TestTable.create_table() 而无需修改它TestTable.create_table()
except Exception as e:print(fError: {e})# 如果连接已关闭这里的关闭操作是多余的因为db.close()在连接关闭时不会引发错误if db.is_closed():db.close() # 实际上这里的检查是多余的因为db在异常发生前应该是打开的else:db.rollback() # 如果有事务在执行并且需要回滚的话但在这个场景中通常没有显式开启的事务
finally:# 无论是否发生异常都要确保数据库连接被关闭if not db.is_closed():db.close()
1-4、用SQLAlchemy库
略该库本身不支持直接创建数据库需要借助其他第三方库如PyMySQL
2、删除 现需在MySQL服务器上删除已有数据库test_database以下为借助第三方库实现
2-1、用mysql-connector-python库
import mysql.connector
# MySQL服务器连接参数
config {user: root,password: 123456, # 在此输入你的MySQL密码请自行修改host: 127.0.0.1,database: mysql # 如果要指定数据库
}
# 连接到MySQL服务器
try:connection mysql.connector.connect(**config)cursor connection.cursor()# 执行SQL语句来删除test_database数据库sql DROP DATABASE IF EXISTS test_databasecursor.execute(sql)# 提交事务connection.commit()print(Database test_database deleted successfully.)
except mysql.connector.Error as error:print(fError: {error})
finally:# 关闭游标和连接if connection.is_connected():cursor.close()connection.close()
2-2、用PyMySQL库
import pymysql
# MySQL服务器连接参数
config {user: root, # 替换为你的MySQL用户名password: 123456, # 替换为你的MySQL密码host: 127.0.0.1, # 替换为你的MySQL服务器地址port: 3306, # 如果你的MySQL不是默认端口需要指定charset: utf8mb4, # 设置字符集cursorclass: pymysql.cursors.DictCursor # 使用字典游标这不是必需的
}
# 连接到MySQL服务器注意这里我们没有指定database参数
try:# 因为我们要删除数据库所以不需要连接到特定的数据库connection pymysql.connect(**{k: v for k, v in config.items() if k ! database})with connection.cursor() as cursor:# 执行SQL语句来删除test_database数据库sql DROP DATABASE IF EXISTS test_databasecursor.execute(sql)# 提交事务可省略connection.commit()print(Database test_database deleted successfully.)
except pymysql.MySQLError as error:print(fError: {error})
finally:# 关闭连接if connection:connection.close()
2-3、用PeeWee库
略该库本身不支持直接删除数据库需要借助其他第三方库如PyMySQL
2-4、用SQLAlchemy库
略该库本身不支持直接删除数据库需要借助其他第三方库如PyMySQL
二、数据表操作
1、创建 在MySQL服务器上已有数据库test_database需在该数据库中创建数据表myelsa_table以下为借助第三方库实现
1-1、用mysql-connector-python库
import mysql.connector
# 数据库连接配置
config {user: root, # 替换为你的MySQL用户名password: 123456, # 替换为你的MySQL密码host: 127.0.0.1, # 如果数据库在远程服务器上请替换为相应的主机名或IP地址database: test_database, # 数据库名raise_on_warnings: True
}
# 连接到数据库
cnx mysql.connector.connect(**config)
cursor cnx.cursor()
# 创建数据表的SQL语句
create_table_query
CREATE TABLE IF NOT EXISTS myelsa_table ( name VARCHAR(255) NOT NULL, ID_Card VARCHAR(255) NOT NULL, age INT NOT NULL, city VARCHAR(255) NOT NULL, PRIMARY KEY (ID_Card) -- 如果ID_Card字段是唯一的可以设为主键否则可以移除这行
) ENGINEInnoDB DEFAULT CHARSETutf8mb4; # 执行SQL语句
cursor.execute(create_table_query)
# 提交更改如果使用了事务
cnx.commit()
# 关闭连接
cursor.close()
cnx.close()
print(Table myelsa_table created successfully!)
1-2、用PyMySQL库
import pymysql
# 数据库连接配置
config {user: root, # 替换为你的MySQL用户名password: 123456, # 替换为你的MySQL密码host: 127.0.0.1, # 如果数据库在远程服务器上请替换为相应的主机名或IP地址database: test_database, # 数据库名charset: utf8mb4, # 字符集设置cursorclass: pymysql.cursors.DictCursor # 使用字典游标
}
# 连接到数据库
connection pymysql.connect(**config)
try:with connection.cursor() as cursor:# 创建数据表的SQL语句create_table_query CREATE TABLE IF NOT EXISTS myelsa_table ( name VARCHAR(255) NOT NULL, ID_Card VARCHAR(255) NOT NULL, age INT NOT NULL, city VARCHAR(255) NOT NULL, PRIMARY KEY (ID_Card) -- 如果ID_Card字段是唯一的可以设为主键 ) ENGINEInnoDB DEFAULT CHARSETutf8mb4; # 执行SQL语句cursor.execute(create_table_query)# 提交更改对于自动提交模式这一步可能不是必须的connection.commit()
finally:connection.close()print(Table myelsa_table created successfully!)
1-3、用PeeWee库
from peewee import *
# 数据库连接配置
db MySQLDatabase(test_database, userroot, password123456, host127.0.0.1)
# 定义模型
class MyElsaTable(Model):name CharField(max_length255, nullFalse)ID_Card CharField(max_length255, uniqueTrue) # 假设ID_Card是唯一的age IntegerField(nullFalse)city CharField(max_length255, nullFalse)class Meta:database db
# 连接到数据库
db.connect()
# 创建表如果表不存在
db.create_tables([MyElsaTable])
# 关闭数据库连接在 Peewee 中通常不需要显式关闭连接因为它会自动管理连接池
db.close()
print(Table myelsa_table created successfully!)
1-4、用SQLAlchemy库
from sqlalchemy import create_engine, Column, Integer, String, MetaData
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker
# 数据库连接配置使用 SQLAlchemy 的 URI 格式
DATABASE_URI mysqlpymysql://root:123456127.0.0.1/test_database?charsetutf8mb4
# 创建一个引擎实例
engine create_engine(DATABASE_URI, echoTrue) # echoTrue 用于显示生成的 SQL 语句调试时可以打开
# 创建基类
Base declarative_base()
# 定义模型类
class MyElsaTable(Base):__tablename__ myelsa_tablename Column(String(255), nullableFalse)ID_Card Column(String(255), primary_keyTrue) # 设置为主键age Column(Integer, nullableFalse)city Column(String(255), nullableFalse)
# 创建表如果表不存在
Base.metadata.create_all(engine)
# 如果你想要使用 ORM 来进行操作可以创建一个 session 类
Session sessionmaker(bindengine)
session Session()
# 这里不需要执行 SQL 语句或提交更改因为 create_all 方法会自动处理
# 关闭 session如果需要的话但在这种情况下我们并没有进行任何 ORM 操作
# session.close()
print(Table myelsa_table created successfully!)
2、删除 在MySQL服务器上已有数据库test_database且该数据库下已有数据表myelsa_table现需删除数据表myelsa_table以下为借助第三方库实现
2-1、用mysql-connector-python库
import mysql.connector
# 数据库连接配置
config {user: root, # 替换为你的MySQL用户名password: 123456, # 替换为你的MySQL密码host: 127.0.0.1, # 如果数据库在远程服务器上请替换为相应的主机名或IP地址database: test_database, # 数据库名
}
try:# 连接到数据库cnx mysql.connector.connect(**config)cursor cnx.cursor()# 执行SQL语句来删除表drop_table_query DROP TABLE IF EXISTS myelsa_table;cursor.execute(drop_table_query)# 提交更改在这个例子中删除表不需要显式提交因为不是事务的一部分# 但如果你之前做了其他更改这里可以调用cnx.commit()print(Table myelsa_table deleted successfully!)
except mysql.connector.Error as err:print(fError: {err})
finally:# 关闭游标和连接if cursor:cursor.close()if cnx.is_connected():cnx.close()
2-2、用PyMySQL库
import pymysql
# 数据库连接配置
config {user: root, # 替换为你的MySQL用户名password: 123456, # 替换为你的MySQL密码host: 127.0.0.1, # 如果数据库在远程服务器上请替换为相应的主机名或IP地址database: test_database, # 数据库名charset: utf8mb4, # 设置字符集可选cursorclass: pymysql.cursors.DictCursor # 使用字典游标可选
}
try:# 连接到数据库connection pymysql.connect(**config)with connection.cursor() as cursor:# 执行SQL语句来删除表drop_table_query DROP TABLE IF EXISTS myelsa_table;cursor.execute(drop_table_query)# 提交更改在这个例子中删除表不需要显式提交因为不是事务的一部分# 但如果你之前做了其他更改并且它们是在一个事务中这里可以调用 connection.commit()print(Table myelsa_table deleted successfully!)
except pymysql.MySQLError as err:print(fError: {err})
finally:# 关闭连接if connection.open:connection.close()
2-3、用PeeWee库
# 注意这里需要借助扩展库peewee-mysql需提前安装
from peewee import *
# 数据库连接配置
db MySQLDatabase(test_database,userroot,password123456,host127.0.0.1
)
try:# 连接到数据库 db.connect()# 创建一个用于执行原始 SQL 的游标 db.execute_sql(DROP TABLE IF EXISTS myelsa_table;)# Peewee 没有直接的“提交”操作因为对于 DDL数据定义语言语句如 DROP TABLE # 它们通常是立即执行的不需要事务提交。 print(Table myelsa_table deleted successfully!)
except peewee.OperationalError as e:print(fError: {e})
finally:# 关闭数据库连接 db.close()
2-4、用SQLAlchemy库
from sqlalchemy import create_engine, MetaData, Table
# 数据库连接配置
config {user: root, # 替换为你的MySQL用户名password: 123456, # 替换为你的MySQL密码host: 127.0.0.1, # 如果数据库在远程服务器上请替换为相应的主机名或IP地址database: test_database, # 数据库名dialect: mysql # 使用mysql方言
}
# 创建连接字符串
connection_string f{config[dialect]}pymysql://{config[user]}:{config[password]}{config[host]}/{config[database]}
try:# 创建引擎engine create_engine(connection_string)# 使用引擎连接到数据库with engine.connect() as conn:# 创建元数据对象metadata MetaData()# 定义要删除的表如果已知表结构可以创建完整的 Table 对象# 但为了简单地删除表我们只需要表名table_name myelsa_table# 使用 SQLAlchemy 的反射机制来获取 Table 对象如果需要# 这里我们直接执行原始 SQL 语句来删除表# 执行SQL语句来删除表drop_table_query fDROP TABLE IF EXISTS {table_name};conn.execute(drop_table_query)print(Table myelsa_table deleted successfully!)
except Exception as e:print(fError: {e})# 在 with 语句结束后连接会自动关闭所以不需要显式关闭连接
三、推荐阅读
1、Python函数之旅
2、Python算法之旅
3、博客个人主页 文章转载自: http://www.morning.tlnkz.cn.gov.cn.tlnkz.cn http://www.morning.msxhb.cn.gov.cn.msxhb.cn http://www.morning.pzjfz.cn.gov.cn.pzjfz.cn http://www.morning.xnpml.cn.gov.cn.xnpml.cn http://www.morning.wjlhp.cn.gov.cn.wjlhp.cn http://www.morning.junyaod.com.gov.cn.junyaod.com http://www.morning.lflnb.cn.gov.cn.lflnb.cn http://www.morning.jmbfx.cn.gov.cn.jmbfx.cn http://www.morning.nynyj.cn.gov.cn.nynyj.cn http://www.morning.ejknty.cn.gov.cn.ejknty.cn http://www.morning.srckl.cn.gov.cn.srckl.cn http://www.morning.fxzlg.cn.gov.cn.fxzlg.cn http://www.morning.xlxmy.cn.gov.cn.xlxmy.cn http://www.morning.fnssm.cn.gov.cn.fnssm.cn http://www.morning.tkkjl.cn.gov.cn.tkkjl.cn http://www.morning.byjwl.cn.gov.cn.byjwl.cn http://www.morning.lpcpb.cn.gov.cn.lpcpb.cn http://www.morning.cjcry.cn.gov.cn.cjcry.cn http://www.morning.tfsyk.cn.gov.cn.tfsyk.cn http://www.morning.qrlsy.cn.gov.cn.qrlsy.cn http://www.morning.kntsd.cn.gov.cn.kntsd.cn http://www.morning.qnzld.cn.gov.cn.qnzld.cn http://www.morning.jopebe.cn.gov.cn.jopebe.cn http://www.morning.pzrrq.cn.gov.cn.pzrrq.cn http://www.morning.bqwnp.cn.gov.cn.bqwnp.cn http://www.morning.rdnkx.cn.gov.cn.rdnkx.cn http://www.morning.pmwhj.cn.gov.cn.pmwhj.cn http://www.morning.ktnt.cn.gov.cn.ktnt.cn http://www.morning.qnbck.cn.gov.cn.qnbck.cn http://www.morning.wkcl.cn.gov.cn.wkcl.cn http://www.morning.cfpq.cn.gov.cn.cfpq.cn http://www.morning.ysskn.cn.gov.cn.ysskn.cn http://www.morning.pswzc.cn.gov.cn.pswzc.cn http://www.morning.gzzncl.cn.gov.cn.gzzncl.cn http://www.morning.ndlww.cn.gov.cn.ndlww.cn http://www.morning.gybnk.cn.gov.cn.gybnk.cn http://www.morning.wmpw.cn.gov.cn.wmpw.cn http://www.morning.flfxb.cn.gov.cn.flfxb.cn http://www.morning.ryxyz.cn.gov.cn.ryxyz.cn http://www.morning.bctr.cn.gov.cn.bctr.cn http://www.morning.pycpt.cn.gov.cn.pycpt.cn http://www.morning.wnjsp.cn.gov.cn.wnjsp.cn http://www.morning.mjdbd.cn.gov.cn.mjdbd.cn http://www.morning.mhnb.cn.gov.cn.mhnb.cn http://www.morning.trfh.cn.gov.cn.trfh.cn http://www.morning.rtsd.cn.gov.cn.rtsd.cn http://www.morning.nkyqh.cn.gov.cn.nkyqh.cn http://www.morning.qxnns.cn.gov.cn.qxnns.cn http://www.morning.tnqk.cn.gov.cn.tnqk.cn http://www.morning.rgxll.cn.gov.cn.rgxll.cn http://www.morning.zfkxj.cn.gov.cn.zfkxj.cn http://www.morning.qgwdc.cn.gov.cn.qgwdc.cn http://www.morning.fsnhz.cn.gov.cn.fsnhz.cn http://www.morning.nqmwk.cn.gov.cn.nqmwk.cn http://www.morning.skcmt.cn.gov.cn.skcmt.cn http://www.morning.flqkp.cn.gov.cn.flqkp.cn http://www.morning.zhishizf.cn.gov.cn.zhishizf.cn http://www.morning.xfxlr.cn.gov.cn.xfxlr.cn http://www.morning.xqkcs.cn.gov.cn.xqkcs.cn http://www.morning.qhfdl.cn.gov.cn.qhfdl.cn http://www.morning.qtzqk.cn.gov.cn.qtzqk.cn http://www.morning.qgxnw.cn.gov.cn.qgxnw.cn http://www.morning.dzpnl.cn.gov.cn.dzpnl.cn http://www.morning.wsnbg.cn.gov.cn.wsnbg.cn http://www.morning.rlzxr.cn.gov.cn.rlzxr.cn http://www.morning.wqbrg.cn.gov.cn.wqbrg.cn http://www.morning.xdjsx.cn.gov.cn.xdjsx.cn http://www.morning.kynf.cn.gov.cn.kynf.cn http://www.morning.dkqbc.cn.gov.cn.dkqbc.cn http://www.morning.xckdn.cn.gov.cn.xckdn.cn http://www.morning.zrpys.cn.gov.cn.zrpys.cn http://www.morning.rfjmy.cn.gov.cn.rfjmy.cn http://www.morning.cgtfl.cn.gov.cn.cgtfl.cn http://www.morning.zcfsq.cn.gov.cn.zcfsq.cn http://www.morning.hxftm.cn.gov.cn.hxftm.cn http://www.morning.mftdq.cn.gov.cn.mftdq.cn http://www.morning.mrpqg.cn.gov.cn.mrpqg.cn http://www.morning.c7622.cn.gov.cn.c7622.cn http://www.morning.ljmbd.cn.gov.cn.ljmbd.cn http://www.morning.nwfpl.cn.gov.cn.nwfpl.cn