博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Python sql数据的增删改查简单操作
阅读量:4625 次
发布时间:2019-06-09

本文共 2134 字,大约阅读时间需要 7 分钟。

 

1.insert

import mysql.connectorimport osimport codecs#设置数据库用户名和密码user='root';#用户名pwd='root';#密码host='localhost';#ip地址db='mysql';#所要操作数据库的名字charset='UTF-8'cnx=mysql.connector.connect(user=user, password=pwd, host=host, database=db)#设置游标cursor=cnx.cursor(dictionary=True)#插入数据def insert(table_name, insert_dict):    param=' ';    value=' ';    if(isinstance(insert_dict, dict)):        for key in insert_dict.keys():            param=param+key+','            value=value+insert_dict[key]+','        param=param[:-1]        value=value[:-1]    sql="insert into %s (%s) values(%s)"%(table_name,param,value)    cursor.execute(sql)    id=cursor.lastrowid    cnx.commit()    return id

2.delete

def delete(table_name, where=' '):    if(where!=' '):        str='where'        for key_value in where.keys():            value=where[key_value]            str=str+' '+key_value+'='+value+' '+'and'        where=str[:-3]        sql='delete from %s %s'%(table_name, where)        cursor.execute(sql)        cnx.commit()

3.获取数据库信息

#取得数据库信息# print(select({'table':'gelixi_help_type','where':{'help_show': '1'}},'type_name,type_id'))def select(param,fields='*'):    table=param['table']    if('where' in param):        thewhere=param['where']        if(isinstance (thewhere,dict)):            keys=thewhere.keys()            str='where';            for key_value in keys:                value=thewhere[key_value]                str=str+' '+key_value+'='+value+' '+'and'                where=str[:-3]    else:    where=''    sql="select %s from %s %s"%(fields,table,where)    cursor.execute(sql)    result=cursor.fetchall()    return result

4.显示

#显示建表语句#table string 表名#return string 建表语句def showCreateTable(table):    sql='show create table %s'%(table)    cursor.execute(sql)    result=cursor.fetchall()[0]    return result['Create Table']#print(showCreateTable('gelixi_admin'))#显示表结构语句def showColumns(table):    sql='show columns from %s '%(table)    print(sql)    cursor.execute(sql)    result=cursor.fetchall()  dict1={}    for info in result:        dict1[info['Field']]=info    return dict1

转载于:https://www.cnblogs.com/guohaojintian/p/5994472.html

你可能感兴趣的文章
使用ssh和putty操控远程的linux server
查看>>
BZOJ1499: [NOI2005]瑰丽华尔兹
查看>>
过滤器
查看>>
Redis是什么?
查看>>
JavaScript 学习总结
查看>>
iOS开发——UI进阶篇(十)导航控制器、微博详情页、控制器的View的生命周期...
查看>>
多线程(四)线程生命周期和线程池
查看>>
fetch的用法
查看>>
2017.08.11【NOIP提高组】模拟赛B组 小X的佛光
查看>>
【转】[精华] 跟我一起写 Makefile
查看>>
排序俩种方法
查看>>
MVC 三级联动
查看>>
JPA 已作废的SQLQuery.class、setResultTransformer方法替换
查看>>
20190402——第一场UPC团队训练
查看>>
爱奇艺视频广告拦截失败,发文共商大计
查看>>
洛谷1144 最短路计数
查看>>
BZOJ 1207: [HNOI2004]打鼹鼠
查看>>
堆排序
查看>>
android下网络通信流程
查看>>
Spring+shiro session与线程池的坑
查看>>