一、python 连接mysql多层结构:
目录文件介绍:
sqlexec sql执行操作,例:增删改查
table 数据库表模块 一个表一个模块
index.py 主文件
conf.py 数据库连接信息
目录结构如下:
-rw-r--r-- 1 root root 167 Jun 22 20:36 conf.py
-rw-r--r-- 1 root root 244 Jun 22 20:36 conf.pyc-rw-r--r-- 1 root root 594 Jun 22 20:35 index.pydrwxr-xr-x 2 root root 4096 Jun 22 20:36 sqlexecdrwxr-xr-x 2 root root 4096 Jun 22 20:39 table./sqlexec:total 12-rw-r--r-- 1 root root 0 Jun 22 18:48 __init__.py-rw-r--r-- 1 root root 138 Jun 22 18:48 __init__.pyc-rw-r--r-- 1 root root 911 Jun 22 20:21 sql_exec.py-rw-r--r-- 1 root root 1690 Jun 22 20:21 sql_exec.pyc./table:total 12-rw-r--r-- 1 root root 0 Jun 22 18:48 __init__.py-rw-r--r-- 1 root root 130 Jun 22 18:48 __init__.pyc-rw-r--r-- 1 root root 1246 Jun 22 19:57 users.py-rw-r--r-- 1 root root 1782 Jun 22 19:57 users.pyc二、具体脚本内容:
1、index.py
#!/usr/bin/python27
#coding:utf-8import os,sysfrom table.users import usersdef main(): username = raw_input('username:') password = raw_input('password:') check = users() result = check.checkvalidate(username,password) if not result: print('用户名密码错误') else: print('欢迎登录后台管理系统') user_list = check.get_dict_user_info(0,'') for key in user_list: for item in key.items(): print(item)if __name__ == '__main__': os.system('clear') main()2、 conf.py
#!/usr/bin/python27
#coding=utf-8conf_dict = {'host':'127.0.0.1', 'user':'root', 'passwd':'root', 'db':'yunwei' }3、table目录下users.py
#!/usr/bin/python27
#coding:utf-8import os,syssys.path.append("..")from sqlexec.sql_exec import mysql_execclass users(object): def __init__(self): self.__result = mysql_exec() def get_dict_user_info(self,flag,user): if flag == 1: sql = "select * from users where user_name=%s" res = self.__result.get_dict(sql,user) elif flag == 0: sql = "select * from users" res = self.__result.get_dict(sql,'') else: res = "the flag is error" return res def get_one_user_info(self,flag,user): if flag == 1: sql = "select * from users where user_name=%s" res = self.__result.get_one(sql,user) elif flag == 0: sql = "select * from users" res = self.__result.get_one(sql,'') else: res = "the flag is error" return res def checkvalidate(self,user,passwd): sql = "select user_name,password from users where user_name=%s and password=md5(%s)" params = (user,passwd,) res = self.__result.get_one(sql,params) return res4、sqlexec目录下sql_exec.py
#!/usr/bin/python27
#coding:utf-8import os,sysimport MySQLdbsys.path.append('..')import confclass mysql_exec(object): def __init__(self): self.__conn = conf.conf_dict def __connect(self): try: conn = MySQLdb.connect(**self.__conn) except Exception,e: print(e) sys.exit('connect failed') cur = conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) return cur cur.close() conn.close() def get_dict(self,sql,params): res = self.__connect() if params != '': res.execute(sql,params) else: res.execute(sql) data = res.fetchall() return data def get_one(self,sql,params): res = self.__connect() if params != '': res.execute(sql,params) else: res.execute(sql) data = res.fetchone() return data