代码简单,不多赘述
import MySQLdb
class Mysqlexc():
database_name = 'payment'
host = '1.1.1.2'
port = '3306'
username = 'root'
password = '123456'
charset = 'utf8'
def __init__(self):
pass
def connectdb(self, host='1.1.1.2', user='root', passwd='123456', db='db', charset='utf8'):
"""
connect to userdb use spacial params
:param host:db hostip
:param user:db user name
:param passwd:user password
:param db:spacial db name
:param charset:chart set like 'utf8'
:return:
"""
conn = MySQLdb.connect(host=host, user=user, passwd=passwd, db=db, charset=charset)
cur = conn.cursor()
return conn, cur
def conn_close(self, conn):
"""
Just close db connection
:param conn: db connection
:return:
"""
if conn != None:
conn.close()
def cursor_close(self, cursor):
if cursor != None:
cursor.close()
def close(self, conn, cursor):
"""
close all of db connect and cursor
:param conn:db connection
:param cursor: db cursor
:return: None
"""
self.cursor_close(cursor)
self.conn_close(conn)
def exc_sql(self, sqlcmd):
"""
:param sqlcmd: excute sql command
:return:excute result and result tuple
"""
conn, cursor = self.connectdb()
result = cursor.execute(sqlcmd)
resline = cursor.fetchall()
print(result)
for row in resline:
print(row)
return result, resline
if __name__ == '__main__':
exs = Mysqlexc()
con, cur = exs.connectdb()
exs.exc_sql('SHOW TABLES')
exs.close(cur, con)