Import Pymysql
Import logging
Import Sys
# Join the Log
#获取logger实例
Logger = Logging.getlogger ("Basespider")
# Specify output format
Formatter = logging. Formatter ('% (asctime) s\
% (levelname) -8s:% (message) s ')
# file Log
File_handler = logging. Filehandler ("BaseSpider.log")
File_handler.setformatter (Formatter)
# console Log
Console_handler = logging. Streamhandler (Sys.stdout)
Console_handler.setformatter (Formatter)
# Add a specific log processor for Logge
Logger.addhandler (File_handler)
Logger.addhandler (Console_handler)
Logger.setlevel (Logging.info)
Class DBHelper:
# constructor
def __init__ (self, host= ' 127.0.0.1 ', user= ' root ',
Pwd= ' 123456 ', db= ' TestDB '):
Self.host = Host
Self.user = user
Self.pwd = pwd
SELF.DB = db
Self.conn = None
Self.cur = None
# Connect to Database
def connectdatabase (self):
Try
Self.conn = Pymysql.connect (Self.host, Self.user,
Self.pwd, self.db,charset= ' UTF8 ')
Except
Logger.error ("Connectdatabase failed")
Return False
Self.cur = Self.conn.cursor ()
Return True
# Close the database
def close (self):
# If data is turned on, it is off; otherwise no action
If Self.conn and Self.cur:
Self.cur.close ()
Self.conn.close ()
Return True
# The SQ statement that executes the database, mainly used to do the insert operation
def execute (self, SQL, Params=none):
# Connect to Database
Self.connectdatabase ()
Try
If Self.conn and Self.cur:
# normal logic, execute SQL, commit operation
Self.cur.execute (SQL, params)
Self.conn.commit ()
Except
Logger.error ("Execute failed:" +sql)
Logger.error ("params:" +params)
Self.close ()
Return False
Return True
# Used to query table data
def fetchall (self, SQL, Params=none):
Self.execute (Sql,params)
Return Self.cur.fetchall ()
if __name__ = = ' __main__ ':
DBHelper = DBHelper ()
# Create a table for a database
sql = "CREATE TABLE Maoyan (' ID ' varchar (8), \
' title ' varchar (50), \
' Star ' varchar (200), \
' Time ' varchar, primary key (' ID ')); "
result = Dbhelper.execute (Sql,none)
If result:
Logger.info ("Maoyan table creation succeeded")
Else
Logger.error ("Maoyan table creation failed")
Python operation MySQL package into class