python sql語句封裝連接mysql


進行了代碼優化,歡迎評審
#!/usr/bin/python
# -*- coding:utf-8 -*-
import logging
logging.basicConfig(level=logging.INFO)
 
class baselib(json.JSONEncoder):
def __init__(self):
self.conn = mysql.connector.connect(host='192.1.1.1',port=3306,user='root',passwd='123456',db='user',charset="utf8")
 
def query(self,sql):
try:
self.cursor = self.conn.cursor(dictionary=True ) #返回數據為dict
data = self.cursor.execute(sql)
data = self.cursor.fetchone()
data = json.dumps(data,cls=CJsonEncoder).decode("unicode-escape")
except mysql.connector.Error as e:
print ('Error : {}'.format(e))
finally:
print 'Connect wemedia closed in finally'
return data

def GetBitradeSqlAll(self,sql):
try:
self.cursor = self.conn.cursor()
data = self.cursor.execute(sql)
data = self.cursor.fetchall()
data = json.dumps(data,cls=CJsonEncoder).decode("unicode-escape")
except mysql.connector.Error as e:
print ('Error : {}'.format(e))
finally:
print 'Connect wemedia closed in finally'
return data
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
import mysql.connector
class mysqltest(object):
def __init__(self):
pass
 
def selectmysql(self,sql):
global conn,cursor
conn = mysql.connector.connect(host='127.0.0.1',port=3306,user='test',passwd='root@test',db='testuser', use_unicode=True)
try:
cursor = conn.cursor()
# 插入一行記錄,注意MySQL的占位符是%s:
data = cursor.execute(sql)
# 查詢單數據時用
#"%s" '% index
wmid = cursor.fetchone()
# wmid = cursor.fetchall() 查詢多數據時使用
except mysql.connector.Error as e:
print ('Error : {}'.format(e))
finally:
print 'Connect wemedia closed in finally'
return wmid

if __name__ == '__main__':
w= mysqltest()

sql = '''select wm_id from wm_owner_info where wm_owner_info.id =59129'''
data = w.selectmysql(sql)
print data
conn.commit()
cursor.close
conn.close
 
以下為歷史版本
#!/usr/bin/python
# -*- coding: UTF-8 -*-
import mysql.connector
 
class connectMysql(object):  
 
  def ExecNonQuery(sql):
    conn = MySQLdb.connect(host='xxxx',user='xxxx',passwd='xxxx',db='xxxx')
    cursor = conn.cursor()
    cursor.execute(sql)
    res = cursor.fetchone()
    print res
    cursor.close
    conn.close

 

#!/usr/bin/python
# -*- coding: UTF-8 -*-
from connectMysql import connectSQl

class diaoyong(object):
 
  def mysql_query(self,i):
    sad = connectSQl()
    sad.ExecNonQuery('select * from user where id = "%s" ' % i )
 
if __name__ == '__main__':
  w = diaoyong()
  w.mysql_query('5')


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM