Python access MySQL
Class-based definition
"""
tpoic: module, sql 資料規則與限制
date: 2013.08
description:
(1) 針對 MySQL 中 db, table, column 進行定義
"""
import MySQLdb
genome_attr = []
genome_count_attr = {}
genome_attr_constraint = {}
class import_def:
global genome_attr, genome_count_attr, genome_attr_constraint
getDbName = ""
def __init__(self,dbName):
self.getDbName = dbName
self.get_tables()
self.count_attrs_column()
self.get_attr_constraint()
def get_tables(self):
try:
plasmids_db = MySQLdb.connect(host="localhost", user="root", passwd="JKW0620_MySQL")
except:
print "Error: Cann`t reach the mysql server."
return ;
plasmids_cur = plasmids_db.cursor()
try:
plasmids_cur.execute("USE " + self.getDbName)
except:
print "Error: Couldn`t get right databases " + self.getDbName
plasmids_cur.close()
plasmids_db.close()
return ;
plasmids_cur.execute("SHOW TABLES")
getTables = plasmids_cur.fetchall()
for tName in getTables:
if tName[0] not in genome_attr:
genome_attr.append(tName[0])
print "State: Get total tables saved in genome_attr."
plasmids_cur.close()
plasmids_db.close()
def count_attrs_column(self):
plasmids_db = MySQLdb.connect(host="localhost", user="root", passwd="JKW0620_MySQL", db = self.getDbName)
plasmids_cur = plasmids_db.cursor()
getCount = 0
for tableName in genome_attr:
plasmids_cur.execute("SELECT * FROM " + tableName)
getAll = plasmids_cur.fetchall()
for elements in getAll:
getCount = len(elements)
break
genome_count_attr.setdefault(tableName, getCount)
plasmids_cur.close()
plasmids_db.close()
print "State: The column counts of each tables were saved in genome_count_attr."
def get_attr_constraint(self):
plasmids_db = MySQLdb.connect(host="localhost", user="root", passwd="JKW0620_MySQL", db = self.getDbName)
plasmids_cur = plasmids_db.cursor()
getAttrconstraint = {}
for tableName in genome_attr:
getAttrconstraint = {}
plasmids_cur.execute("SELECT * FROM " + tableName)
getAll = plasmids_cur.description
for elements in getAll:
getAttrconstraint.setdefault(elements[0],elements[3])
genome_attr_constraint.setdefault(tableName, getAttrconstraint)
plasmids_cur.close()
plasmids_db.close()
print "State: Both column name and constraint were saved in genome_attr_constraint."
def showDbAndTable(self):
print "-----------------------"
print "Database : " + self.getDbName
print "This dataBase includes " + str(len(genome_attr)) + " tables."
print "The following are all tables: "
for eTables in genome_attr:
print "\t" + eTables
print "-----------------------"
Usage
"""
tpoic: 新增 seq 入 database 中(MySQL)
date: 2013.08
description:
(1) 需要先 import GCSdef(.py) 來進行前置處理
"""
import MySQLdb
import GCSdef
gnome_Name = raw_input("Enter a database name: ")
gcsInit = GCSdef.import_def(gnome_Name)