今晚是第四周的最后一晚,记录一下对数据库接口的整理
import psycopg2
class Connection(object):
"""
管理数据库连接
"""
def __init__(self, dbname, username, password, host,post):
self.conn= psycopg2.connect(
database=dbname, user=username, password=password,
host=host, port=post)
def get_conn(self):
return self.conn
def close_conn(self):
if self.conn is not None:
self.conn.close()
def cursor(self):
cursor = self.conn.cursor()
self.conn.autocommit = True
return cursor
class Backinform(object):
def __init__(self,dbname, username, password, host,post):
self.connection=Connection(dbname, username, password, host,post)
def insert_food(self,user_id, food_url, food_infor, food_name, time):
cursor = self.connection.cursor()
cursor.execute("SELECT * from FOOD_TABLE")
n = cursor.rowcount + 1
str(n)
cursor.execute(
"INSERT INTO FOOD_TABLE(food_id,food_name,food_infor,url,time)VALUES('%s','%s','%s','%s','%s')" % (
n, food_name, food_infor, food_url, time))
self.connection.conn.commit()
cursor.execute("INSERT INTO RELATION_TABLE(id,food_id,relationship)VALUES('%s','%s','%s')" % (user_id, n, '0'))
self.connection.conn.commit()
self.connection.close_conn()
database = "USER_TABLE"
user = 'postgres'
password = '123'
host = '127.0.0.1'
port = '5432'
# 数据库调用接口类
backinform = Backinform(database, user, password, host, port)