error while writing to a Mysql wih python NetCDF

我怕爱的太早我们不能终老 提交于 2020-01-16 20:00:20

问题


#!/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()

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..

Here is the detail.

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'

回答1:


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



来源:https://stackoverflow.com/questions/32417520/error-while-writing-to-a-mysql-wih-python-netcdf

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!