最近学习python,记录下自己写学习python的代码和心得,自己写了一个使用python mysql 的查询语句和做的一个db_config.py 配置信息。
1、db_config.py 配置文件
1 #/usr/bin/python 2 3 class mysql_config(): 4 ‘‘‘def __init__(self,name): 5 #print ‘aaaa‘ 6 self.name = name 7 print name 8 ‘‘‘ 9 def get_config(self,name): 10 self.name = name 11 config ={ 12 ‘testdb‘:{ 13 ‘host‘:‘192.168.6.6‘, 14 ‘user‘:‘php2‘, 15 ‘passwd‘:‘123456‘, 16 ‘db‘:‘testdb‘, 17 ‘port‘:3307, 18 }, 19 } 20 return config[name]
2、自己封装的mysql 连接class db_mysql 先练练手。
1 #/uer/bin/python 2 3 import MySQLdb; 4 from db_config import mysql_config 5 m_config = mysql_config() 6 class db_mysql(): 7 def __init__(self): 8 print ‘class:db_mysql -import -true‘ 9 10 def connect(self,name): 11 #self.sql = sql 12 self.name = name 13 try: 14 #self.config = m_config.abc(name) 15 config = m_config.get_config(name) 16 db = MySQLdb.connect(**config) 17 cursor = db.cursor() 18 #cursor.execute(sql) 19 except MySQLdb.connector.Error as err: 20 print("Something went wrong: {}".format(err)) 21 return cursor 22 23 def execute(self,cursor,sql): 24 cursor.execute(sql) 25 return cursor 26 27 def fetchall(self,cursor): 28 data = cursor.fetchall() 29 return data 30 31 def fetchone(self,cursor): 32 return cursor.fetchone()
3、测试能否获取到数据。。。。。。。
1 #/usr/bin/python/ 2 3 from mysql import db_mysql 4 mysql_obj = db_mysql() 5 6 sql ="SELECT * FROM test WHERE `p_id` = ‘1000‘ LIMIT 10"; 7 cursor_connect = mysql_obj.connect(‘testdb‘) 8 cursor_execute = mysql_obj.execute(cursor_connect,sql) 9 data = mysql_obj.fetchall(cursor_execute) 10 11 print data;
python学习之 -mysql 连接和db_config配置
原文:http://www.cnblogs.com/zhangshl/p/4095576.html