写入带有Mysql的wih python NetCDF时出错 [英] error while writing to a Mysql wih python NetCDF

查看:111
本文介绍了写入带有Mysql的wih python NetCDF时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#!/usr/bin/env python3
import datetime as dt  # Python standard library datetime  module
import numpy as np
from netCDF4 import Dataset  # http://code.google.com/p/netcdf4-python/
import matplotlib.pyplot as plt
#from mpl_toolkits.basemap import Basemap, addcyclic, shiftgrid
import mysql.connector as sql
from mysql.connector import errorcode
import sys
import getpass
import hashlib
import os
import netCDF4
import sys, traceback

def dbInsertGlobalAttributeCreateTable(cursor):
    ##Table name parameter is required later
    TABLES = {}
    TABLES['cmip5gloAtt'] = (
        "CREATE TABLE `cmip5gloAtt` ("
        " `id` int(100) AUTO_INCREMENT NOT NULL,"
        " `institution` varchar(100) NOT NULL,"
        " `source` varchar(100) NOT NULL,"
        " `forcing` varchar(100) NOT NULL,"
        " `parent_experiment_id` varchar(100) NOT NULL,"
        " `branch_time` varchar(100) NOT NULL,"
        " `contact` varchar(100) NOT NULL,"
        " `initialization_method` varchar(100) NOT NULL,"
        " `physics_version` varchar(100) NOT NULL,"
        " `tracking_id` varchar(100) NOT NULL,"
        " `experiment` varchar(100) NOT NULL,"
        " `creation_date` varchar(100) NOT NULL,"
        " `Conventions` varchar(100) NOT NULL,"
        " `table_id` varchar(100) NOT NULL,"
        " `parent_experiment` varchar(100) NOT NULL,"
        " `realization` varchar(100) NOT NULL,"
    " `cmor_version` varchar(100) NOT NULL,"
    " `comments` varchar(100) NOT NULL,"
    " `history` varchar(100) NOT NULL,"
    " `references` varchar(100) NOT NULL,"
    " `title` varchar(100) NOT NULL,"
    "  PRIMARY KEY (`id`)"
") ENGINE=InnoDB")


for tableName, query in TABLES.items():
    try:
        cursor.execute(query)
        return True
    except sql.Error as err:
        if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
            print ("Table is already there %s" %(tableName))
            return True
        else:
            print("Error is here %s" %(err.msg))
            return False

def insertAttributeValues(cursor, values):
    tupleValues = tuple(values)

    addRecord = ("INSERT INTO cmip5gloAtt"
             "(institution, source, forcing, parent_experiment_id,     branch_time, contact, initialization_method, physics_version, tracking_id,     experiment, creation_date, Conventions, table_id, parent_experiment,     realization, cmor_version, comments, history, references, title) "
                 "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")

print(tupleValues)

try:
    cursor.execute(addRecord, tupleValues)
except sql.error as err:
    print("Error inserting name %s" %(err.msg))


globalAttributes = ['institution','source', 'forcing', 'parent_experiment_id','branch_time', 'contact', 'initialization_method', 'physics_version', 'tracking_id', 'experiment', 'creation_date', 'Conventions', 'table_id', 'parent_experiment', 'realization', 'cmor_version', 'comments', 'history', 'references', 'title']

valueList = list()

datafilePath = input("File/directory to translate: ").strip()
dbHost = input("Database Host?:")
dbName = input("Database to store NDN name?:")
dbUserName = input("Database username?:")
dbPasswd = getpass.getpass("Database password?:")



print("full path is %s", datafilePath)
print("what is ", os.path.isfile(datafilePath))


if os.path.isfile(datafilePath) is True:
     print ("os path worked")

     fileName = os.path.split(datafilePath)[-1]


     try:

     with netCDF4.Dataset(datafilePath, 'r') as ncFile:

         nc_attrs = ncFile.ncattrs()
         print (nc_attrs)
         for nc_attr in globalAttributes:
             try:
                 print ('\t%s: ' % nc_attr, repr(ncFile.getncattr(nc_attr)))
                 valueList.append(repr(ncFile.getncattr(nc_attr)))
             except:
                 print("NoAttribute: %s" %(nc_attr))
                 valueList.append("No particular value stored")

     except:

     print("Error")

try:
    con = sql.connect(user=dbUserName, database=dbName, password=dbPasswd, host=dbHost)
    cursor = con.cursor()

   if dbInsertGlobalAttributeCreateTable(cursor):

       boolResult = insertAttributeValues(cursor, valueList)
       con.commit()
    print("Return Code %s" %(boolResult))
else:
    print("Creation table failed")

except sql.error as err:
    if err.errno == errorcode.ER_ACCESS_DENIED_CHANGE_USER_ERROR:
        print("Incorrect username")
    elif err.errno == errorcode.ER_BAD_DB_ERROR:
        print("DB is not there")
    else:
        print("Error connecting to DB %s" %(err.msg))

finally:
    con.close()

这是python代码.很抱歉缩进不当. 我正在尝试从NetCDF文件中读取一些信息 并想将其写入MySQL,但出现了一些我无法解决的错误 解决.

It is a python code. I am sorry for improper indentation. I am trying to read some information from a NetCDF file and wanted to write it to MySQL and i got some errors that I cannot solve.

我相信我将所有内容都使用了正确的语法.我不明白为什么会发生这种错误.

I believe that I put everything in correct syntax. I do not understand why such error takes place..

这是细节.

Traceback (most recent call last):
  File "/home/uns/PycharmProjects/netCDF4FileEx/netCDF4Ex.py", line 69, in  insertAttributeValues
   cursor.execute(addRecord, tupleValues)
  File "/usr/lib/python3/dist-packages/mysql/connector/cursor.py", line 515, in execute
    self._handle_result(self._connection.cmd_query(stmt))
  File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 636, in cmd_query
    result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
  File "/usr/lib/python3/dist-packages/mysql/connector/connection.py", line 554, in _handle_result
    raise errors.get_exception(packet)
mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in     your SQL syntax; check the manual that corresponds to your MySQL server     version for the right syntax to use near 'references, title) VALUES    ('\'AORI (Atmosphere and Ocean Research Institute, The' at line 1

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/uns/PycharmProjects/netCDF4FileEx/netCDF4Ex.py", line 120, in     <module>
    boolResult = insertAttributeValues(cursor, valueList)
  File "/home/uns/PycharmProjects/netCDF4FileEx/netCDF4Ex.py", line 70, in     insertAttributeValues
    except sql.error as err:
AttributeError: 'module' object has no attribute 'error'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "/home/uns/PycharmProjects/netCDF4FileEx/netCDF4Ex.py", line 126, in <module>
    except sql.error as err:
AttributeError: 'module' object has no attribute 'error'

推荐答案

REFERENCES MySQL保留字.如果希望将其用作列名,则需要在其两边加上反引号(`).

REFERENCES is a MySQL reserved word. If you wish to use it as a column name you will need to surround it with backticks (`).

这篇关于写入带有Mysql的wih python NetCDF时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆