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

时间:2022-03-09 17:17:21

最近学习python,记录下自己写学习python的代码和心得,自己写了一个使用python mysql 的查询语句和做的一个db_config.py 配置信息。

1、db_config.py 配置文件

 #/usr/bin/python

 class mysql_config():
'''def __init__(self,name):
#print 'aaaa'
self.name = name
print name
'''
def get_config(self,name):
self.name = name
config ={
'testdb':{
'host':'192.168.6.6',
'user':'php2',
'passwd':'',
'db':'testdb',
'port':3307,
},
}
return config[name]

2、自己封装的mysql 连接class db_mysql  先练练手。

 #/uer/bin/python                                                                                                                           

 import MySQLdb;
from db_config import mysql_config
m_config = mysql_config()
class db_mysql():
def __init__(self):
print 'class:db_mysql -import -true' def connect(self,name):
#self.sql = sql
self.name = name
try:
#self.config = m_config.abc(name)
config = m_config.get_config(name)
db = MySQLdb.connect(**config)
cursor = db.cursor()
#cursor.execute(sql)
except MySQLdb.connector.Error as err:
print("Something went wrong: {}".format(err))
return cursor def execute(self,cursor,sql):
cursor.execute(sql)
return cursor def fetchall(self,cursor):
data = cursor.fetchall()
return data def fetchone(self,cursor):
return cursor.fetchone()

3、测试能否获取到数据。。。。。。。

 #/usr/bin/python/                                                                                                                          

 from mysql import db_mysql
mysql_obj = db_mysql() sql ="SELECT * FROM test WHERE `p_id` = '1000' LIMIT 10";
cursor_connect = mysql_obj.connect('testdb')
cursor_execute = mysql_obj.execute(cursor_connect,sql)
data = mysql_obj.fetchall(cursor_execute) print data;