目錄:
  1. 修改PgSQL数据库中表中为关键字的字段名

    修改PgSQL数据库中表中为关键字的字段名

    閱讀時間:全文 505 字,預估用時 3 分鐘
    創作日期:2017-03-30
    文章標籤:
     
    BEGIN

    推荐阅读:配置环境变量.env文件

    前言

      有时候对数据库进行增删改查时会遇到各种莫名奇妙的问题,或许是因为你的字段名用到了sql的关键字.   关于PostgreSQL和SQL:2003、SQL:1999、SQL-92各版本规范的关键字参见网页:关键词详情页 🔗

    需求分析

    1. 让数据库达到最大兼容,凡是保留字的都不能要。
    2. 找出所有字段为关键字的表和字段名,并改字段名为表名_原字段名,如user_level

    功能实现

    1. 爬取关键词详情页的所有关键词。
    2. 获得要修改的数据表
    3. 获得数据表对应的字段名
    4. 修改字段名

    代码实现

    1. 通常项目都会有个.env文件用于存储配置信息。
    # ./.env
    # 连接数据库用
    PG_URL="postgresql://username:password@localhost/dbname"
    1. 主要功能实现,注释讲解。
    #coding:utf-8
    import lxml.html, requests, psycopg2
    
    # 用于搜索并加载.env文件
    from dotenv import load_dotenv, find_dotenv
    load_dotenv(find_dotenv())
    
    # 需要修改的表名,如果为空则修改整个数据库中的所有表
    need_alter_table = ["xxx", "xxxx", "xx", "x"] 
    
    # 用于连接数据库并做修改操作或返回查询结果
    def exc_psql(sql, alter = 0):
    		# 连接数据库
        conn = psycopg2.connect(os.environ.get('PG_URL'))
    		# 赋值操作游标
        cur = conn.cursor()
        try:
    				# 执行sql语句
            cur.execute(sql)
            if not alter:
                data = cur.fetchall()
                return data
    				# 进行提交操作,不提交则此次对数据库的更改无效
            conn.commit()
        finally:
            cur.close()
            conn.close()
    
    if __name__ == "__main__":
        url = u"http://www.php100.com/manual/PostgreSQL8/sql-keywords-appendix.html"
        r = requests.get(url)
    		# 对xml文档解析成dom树
        x = lxml.html.fromstring(r.text)
        # 获取所有的关键字
        ans = x.xpath("//tt[@class='TOKEN']/text()")
        if not any(need_alter_table):
            #获取所有表名
            sql = "select tablename from pg_tables where schemaname='public'"
            sqldata = exc_psql(sql)
            table_name = [list(x)[0] for x in sqldata]
        else:
            table_name = need_alter_table
        for table in table_name:
            #获取所有字段名
            sql = "select column_name from information_schema.columns where table_name='%s';" % table
            sqldata = exc_psql(sql)
            column_name = [list(x)[0] for x in sqldata]
            for col in column_name:
                if col.upper() in ans:
                    print "表名:", table, "字段名:", col
                    #执行更改操作
                    altersql = "alter table %s rename %s to %s" % (table, col, table + '_' + col)
                    exc_psql(altersql, 1)
    FINISH

    隨機文章
    人生倒計時
    default