• python 将Excel导入到oracle


    有的时候我们需要把execl 等其他类型文件导入到数据库中,一般我们会使用一些工具自带的导入工具来实现,但是有的时候使用起来还是不方便,能不能自己写个脚本实现这个功能呢,下面直接上代码:

    使用语音:python

    实现功能:指定数据库连接信息->指定要导入的文件路径->指定要导入的表->动创建表->将execl文件导入到表里面

    具体展示效果如下图所示:

     

    下面附上python的代码:

    1. import pandas as pd
    2. import cx_Oracle
    3. import xlrd2
    4. if __name__ == "__main__":
    5. try:
    6. db_url = input("db_url:")
    7. conn = cx_Oracle.connect(db_url, encoding="UTF-8", nencoding="UTF-8")
    8. cursor = conn.cursor()
    9. file_name = input("file_name:")
    10. table_name = input("table_name:")
    11. insert_line = 0
    12. workbook = xlrd2.open_workbook(file_name)
    13. booksheet = workbook.sheet_by_index(0)
    14. nrows = booksheet.nrows # 行数
    15. ncols = booksheet.ncols # 列数
    16. # 动态生成表
    17. createSql = "create table %s(\n" % table_name
    18. cols = "values("
    19. # values = "% ("
    20. for x in range(ncols):
    21. createSql += "x%s varchar2(1000)" % x
    22. # values += "row_data[%s]" % x
    23. cols += "'%s'"
    24. if x < ncols - 1:
    25. createSql += ",\n"
    26. # values += ",\n"
    27. cols += ",\n"
    28. else:
    29. createSql += "\n)"
    30. # values += "\n )"
    31. cols += "\n)"
    32. # 创建表
    33. sql = "select count(*) num from user_tables where lower(table_name)='%s'" % table_name
    34. cursor.execute(sql)
    35. tableCount = cursor.fetchone()
    36. if tableCount[0] > 0:
    37. print("表已存在")
    38. else:
    39. print("开始创建表")
    40. cursor.execute(createSql)
    41. for i in range(0, nrows):
    42. row_data = booksheet.row_values(i)
    43. if row_data:
    44. inSql = "insert into %s \n" % table_name
    45. values = "values ("
    46. for x in range(ncols):
    47. values += "'%s'" % str(row_data[x])
    48. if x < ncols - 1:
    49. values += ",\n"
    50. else:
    51. values += "\n )"
    52. inSql += values
    53. log = "已插入:%s行" % i
    54. print(log)
    55. cursor.execute(inSql)
    56. conn.commit()
    57. cursor.close()
    58. conn.close()
    59. except Exception as e:
    60. print(e)
    61. cursor.close()
    62. conn.close()

  • 相关阅读:
    JQuery+post+asp.net的三种方法
    对React fiber的理解
    Uniapp矩阵评分组件
    DDR存储器中的一些概念
    几种常用关系型数据库架构和实现原理
    记一次 .NET某报关系统 非托管泄露分析
    jQuery复习
    Linux进程优先级与环境变量初识
    1401 位置编码公式详细理解补充
    vue中插槽的详解
  • 原文地址:https://blog.csdn.net/shiyu1157758655/article/details/126758301