import pymysql
from com.study.common.readConfig import getConfig
host = getConfig("Config.txt", 'mysql', 'host')
port = getConfig("Config.txt", 'mysql', 'port')
user = getConfig("Config.txt", 'mysql', 'user')
password = getConfig("Config.txt", 'mysql', 'password')
database = getConfig("Config.txt", 'mysql', 'db')
db = pymysql.connect(host=host, port=int(port),
user=user, password=password, db=database)
cur = db.cursor()
sql = """create table test (
id int(10) NOT NULL AUTO_INCREMENT,
name char(20) NOT NULL,
age int(11) DEFAULT NULL,
sex char(1) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
cur.execute(sql)
def mysql_insert(sql_insert):
try:
cur.execute(sql_insert)
db.commit()
except:
db.rollback()
def mysql_select(sql_select):
try:
cur.execute(sql_select)
for col in cur.description:
print(col[0], end='\t')
print('\n--------------------------------')
for row in cur:
print(row)
cur.close()
db.close()
except:
print("Error: unable to fecth data")
sql2 = """
insert into test values(2, "陈阳", 22, "男");
"""
sql3 = """
select * from test
"""
mysql_select(sql3)
|