python mysql example_Python_Example_ Pycharm(python) 与 数据库(MySQL) 连接学习/示例
#coding=utf-8#---------------------------------
'''# Author : chu ge
# Function:
#'''
#---------------------------------
importpymysql'''#---------
一、創(chuàng)建表
二、查詢表
SQL_table_read = "show tables;"
三、修改表
SQL_table_update = "alter table add|change|drop ;"
四、刪除表
SQL_table_drop = "drop table ;"
#---------
# CRUD 數(shù)據(jù)
增加 create
查詢 read
修改 update
刪除 delete
一、增加
SQL_data_insert_all = "insert into values(。。。);" # 全插入
SQL_data_insert_single = "insert into values(。。。);"# 缺省插入 單行單列
SQL_data_insert_single_1 = "insert into values(。。。),(。。。),(。。。);"# 缺省插入 多行單列
SQL_data_insert_single_2 = "insert into values(。。。),(。。。),(。。。);" # 缺省插入 多行多列
二、查詢
SQL_data_read = "select * from <> where "
三、修改
SQL_data_update = " update set = where "
SQL_data_update_1 = " update isdelete=1 where " # 邏輯刪除
四、刪除
SQL_data_delete = "delete from where "'''
#------------------
classClass_Mysql_Helper(object):def __init__(self,host,port,user,passwd,db,chaerset='utf8'):
self.host= host #localhost
self.port = port #3306
self.user = user #root
self.passwd = passwd #123
self.db = db #python3
self.charset = chaerset #固定
defMethods_Open(self):#用于建立與數(shù)據(jù)庫的連接
self.conn = pymysql.connect(host =self.host,
port=self.port,
user=self.user,
passwd=self.passwd,
db=self.db
)#操作數(shù)據(jù)庫的游標
self.cursor =self.conn.cursor()defMethods_Close(self):
self.cursor.close()#關閉數(shù)據(jù)表
self.conn.close() #關閉數(shù)據(jù)庫
defMethods_Data_CURD(self,sql,params):try:
self.Methods_Open()
self.cursor.execute(sql,params)
self.conn.commit()
self.Methods_Close()print("OK")except(Exception,error):print(error.message)#重復使用代碼 使用封裝
def Methods_All(self,sql,params=[]):try:
self.Methods_Open()
self.cursor.execute(sql, params)
result=self.cursor.fetchall()
self.Methods_Close()returnresultexcept(Exception, error):print(error.message)'''# ============================================================================
# 測試專用
# ============================================================================'''
if __name__ == "__main__":
NAME=input('請輸入用戶姓名:')
ID=input('請輸入用戶編號:')#調(diào)用 對象
SQL_help = Class_Mysql_Helper("localhost", 3306, "root", "123", "python3")#修改 update
Sql = 'update aa set name=%s where id=%s'Params=[NAME,ID]
SQL_help.Methods_Data_CURD(Sql,Params)#查詢 ead
Sql_read = 'select id,name from aa where id<3'Result=SQL_help.Methods_All(Sql_read)print(Result)
總結
以上是生活随笔為你收集整理的python mysql example_Python_Example_ Pycharm(python) 与 数据库(MySQL) 连接学习/示例的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 新U盘怎么格式化为ntfs 新手教程:U
- 下一篇: 最新华硕怎么设置u盘启动器 华硕电脑如何