判断数据库字段是否为数字
在工作中遇到需要判断数据库某个字段存的数据是否为数字的需求,字段本身为varchar类型,要求存的为“数字”。
cx_Oracle如果提示没有可能需要安装
import pandas as pd import cx_Oracle name = 'bz_xxxx' pwd = 'xxxx' #ip和实例名 tes = '127.0.0.1/orcl' localdb = cx_Oracle.connect(name, pwd, tes) sql = '''SELECt job_id,substr(c15, 1, length(c15) - 1) FROM pb_rp_payout where report_id = '300341' and c6 != '未达监控节点' AND c3 IS NOT NULL AND set_year = '2021' ''' #将sql结果存为list1列表 data = pd.read_sql(sql, localdb) list1 = data.values.tolist() list2 = [] #写一个判断是否为数字的函数 def is_number(str): if str is not None: try: float(str) return True except ValueError: pass return False #遍历列表将结果存到list2列表 for i,v in list1: if v is None or is_number(v): pass else: list2.append(i) #将list2列表写入txt with open('C:\Users\lypzm\Desktop\pyprogram\sql.txt', 'w') as q: for i in list2: q.write(i) q.write('n')