#!/usr/bin/env python
#coding:utf-8
"""
FuncName: JzMySQL.py
Desc: study mysql for python 2.7
Date: 2016-10-11 10:30
Author: johnny
"""
import MySQLdb
class JzMySQL(object):
def __init__(self, DB_HOST, DB_PORT, DB_USER, DB_PWD, DB_NAME):
self.DB_HOST = DB_HOST
self.DB_PORT = DB_PORT
self.DB_USER = DB_USER
self.DB_PWD = DB_PWD
self.DB_NAME = DB_NAME
self.conn = self.getConnection()
def getConnection(self):
return MySQLdb.Connect(
host=self.DB_HOST, #设置MYSQL地址
port=self.DB_PORT, #设置端口号
user=self.DB_USER, #设置用户名
passwd=self.DB_PWD, #设置密码
db=self.DB_NAME, #数据库名
charset='utf8' #设置编码
)
def create(self,createSQL):
"""
:param createSQL: 创建新表
:return:
"""
cursor=self.conn.cursor()
cursor.execute(createSQL)
cursor.close()
self.conn.close()
def query(self, querySQL):
"""
:param querySQL: 查询数值
:return: returnData为元祖数据
#使用 cursor.rowcount 获取结果集的条数
#numrows = int(cursor.rowcount)
#print numrows
# 依次遍历结果集,发现每个元素,就是表中的一条记录,用一个元组来显示
#for returnData_single in returnData:
#print returnData_single
#获取连接对象的描述信息
#print cursor.description
"""
cursor=self.conn.cursor()
cursor.execute(querySQL)
returnData=cursor.fetchall()
cursor.close()
self.conn.close()
return returnData
def update(self, updateSQL):
"""
:param updateSQL: 更新数据
:return:
"""
cursor=self.conn.cursor()
cursor.execute(updateSQL)
self.conn.commit()
cursor.close()
self.conn.close()
if __name__=="__main__":
db=JzMySQL('localhost',3306,'root','root','johnny')
#createSQL ="CREATE TABLE IF NOT EXISTS USER(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))"
#db.create(createSQL)
#updateSQL = "drop table USER "
#updateSQL = "INSERT INTO USER(id,name) VALUES('1','JOHNNY')"
#db.update(updateSQL)
#querySQL = "show tables"
#querySQL = "SELECT VERSION()"
querySQL = "select * from USER"
print db.query(querySQL)
python 操作mysql
最新推荐文章于 2023-10-06 10:09:06 发布