首页 > 学院 > 开发设计 > 正文

python学习之-mysql连接和db_config配置

2019-11-14 17:30:42
字体:
来源:转载
供稿:网友

最近学习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 = name11         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  = sql12         self.name = name13         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 cursor22         23     def execute(self,cursor,sql):24         cursor.execute(sql)25         return cursor26 27     def fetchall(self,cursor):28         data = cursor.fetchall()29         return data30         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;

 


发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表