python - 使用 python NetCDF 写入 Mysql 时出错

标签 python mysql 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,但我遇到了一些我无法写入的错误 解决。

我相信我将所有内容都放在正确的语法中。我不明白为什么会发生这样的错误..

这是详细信息。

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'

最佳答案

引用MySQL reserved word 。如果您希望将其用作列名称,则需要用反引号 (`) 将其括起来。

关于python - 使用 python NetCDF 写入 Mysql 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32417520/

相关文章:

python - 如何在 NetCDF 上应用 xarray u_function 并将二维数组(多个新变量)返回到数据集

python - 如何使 Python 中的 json.dumps 忽略不可序列化的字段

php - 在 PHP 中为 mysql 创建重复行函数

mysql - 对通过连接创建的某些列进行联合?

mysql - 在 MySQL 中合并来自一张表的两个选择查询

R:如何在等面积/折衷世界地图上投影全局二维场?

python - 当我在没有过滤器的情况下在 Dynamodb 中执行 scan() 并仅检索 10 个对象时,它是否仍然访问整个数据库?

python - 从 Python2 到 Python3 的这种解包行为的变化是什么?

Python super() 参数 : why not super(obj)?

r - 如何在 ggplot2 中正确绘制投影网格数据?