언어/python

python + mysql

파아랑새 2018. 6. 29. 22:49
import mysql.connector
from mysql.connector import errorcode
import time
#__________________________________________
def InsertHash(Hash_value):
# connect information
try:
cnx = mysql.connector.connect(
user = "kim", password = "1234",
host = "172.30.1.55"
)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_ACCESS_DENIED_ERROR:
print ("Someting is wrong with your name or passord")
elif err.errno == errorcode.ER_BAD_DB_ERROR:
print ("Database does not exist")
else:
print (err)
else:
print ("MySQL Server 접근 성공 ...")
time.sleep(1)
print ("DB({d}) creating ...".format(d = "Hash_info"))
try:
cursor = cnx.cursor()
create_database_query = ("CREATE DATABASE Hash_info")
cursor.execute(create_database_query)
except mysql.connector.Error as err:
if err.errno == errorcode.ER_DB_CREATE_EXISTS:
print ("생성하고자 하는 DB가 이미 존재 합니다.")
elif err.errno == errorcode.ER_CANT_CREATE_DB:
print ("생성과정에서 에러가 발생했습니다. 프로그램이 강제 종료 됩니다.")
exit(1)
else:
print (err + " 프로그램이 강제로 종료 됩니다.")
exit(1)
else:
cnx.commit()
cursor.close()
print ("create db({}) success ... !!".format("Hash_info"))
# 테이블(table) 생성
finally:
time.sleep(1)
cursor = cnx.cursor()
use_create_query = ("use Hash_info")
cursor.execute(use_create_query)

TABLES = {}
TABLES['Normal_hash'] = (
"CREATE TABLE `Normal_hash` ("
" `md5_proj` varchar(33) NOT NULL,"
" `sha1_proj` varchar(41) NOT NULL"
") ENGINE=InnoDB")

TABLES['malware_hash'] = (
"CREATE TABLE `malware_hash` ("
" `md5_proj` varchar(33) NOT NULL,"
" `sha1_proj` varchar(41) NOT NULL"
") ENGINE=InnoDB")

for name, ddl in TABLES.items():
try:
print ("Creating table {}: ".format(name), end='')
cursor.execute(ddl)
except mysql.connector .Error as err:
if err.errno == errorcode.ER_TABLE_EXISTS_ERROR:
print ("already exists.")
else:
print (err.msg)
else:
print ("테이블 생성 성공 ...")
cursor.close()
cnx.close()
InsertHash(10)