0
#!/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和我有一些錯誤,我不能 解決。寫入Mysql時發生錯誤w python NetCDF
我相信,我把一切都在正確的語法。我不明白爲什麼這樣的錯誤發生..
下面是詳細信息。
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'
謝謝!有效 ! –