index.py 这里只是假设一个模拟登陆# -*- coding: utf-8 -*- """ Created on Sun Nov&
index.py 这里只是假设一个模拟登陆
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 27 18:54:29 2016
这是主程序文件
@author: toby
"""
from model.user import User
def main():
username = "tantianran1"
user = User()
result = user.Check_Username(username)
if not result:
print '用户不存在,请重新登录'
else:
print '登录成功'
if __name__ == "__main__":
main()
user.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 27 19:48:03 2016
对数据库表的处理,py文件名和表名一一对应
所以,在这里的user.py文件是对数据库表为user的处理
@author: toby
"""
import sys
sys.path.append("/home/toby/workspace/date20161128")
from utility.sql_helper import MysqlHelper
class User(object):
def __init__(self):
self.__helper = mysqlHelper()
def Get_data_by_id(self,ids):
sql = "select * from user where id=%s"
params = (ids,)
return self.__helper.Get_One_Data(sql,params)
def Check_Username(self,name):
sql = "select * from user where name=%s"
params = (name,)
return self.__helper.Get_One_Data(sql,params)
'''
a = User()
print a.Check_Username('tantianran')
'''
sql_helper.py
# -*- coding: utf-8 -*-
"""
Created on Sun Nov 27 18:57:44 2016
数据处理层,处理数据的最底层,例如增删改查的功能
@author: toby
"""
import MySQLdb
class MysqlHelper(object):
def __init__(self):
hosts,users,passWord,dbname = '127.0.0.1','root','1qaz#EDC','test_db'
self.conn = MySQLdb.connect(host=hosts,user=users,passwd=password,db=dbname)
self.cur = self.conn.cursor(MySQLdb.cursors.DictCursor)
def Get_Dict_data(self,sql,params):
self.cur.execute(sql,params)
data = self.cur.fetchall() #fetchall()获取所有数据
self.cur.close()
self.conn.close()
return data
def Get_One_Data(self,sql,params):
self.cur.execute(sql,params)
data = self.cur.fetchone() #fetchone()是获取一条数据
self.cur.close()
self.conn.close()
return data
--结束END--
本文标题: 用python操作mysql数据库(之代码归类)
本文链接: https://lsjlt.com/news/47658.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-10-23
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
2024-10-22
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0