python连接MySQL数据库
'''
python连接mysqldemo
1.获取数据库
2.获取记录
3.增加记录
4.修改记录
5.删除记录
6............
'''
__author__ = 'xiaolong'
import pymysql
class MysqlDemo(object):
def __init__(self,host,username,password,dbname):
self.conn = pymysql.connect(host,username,password,dbname,charset='utf8')
self.cursor = self.conn.cursor()
def update(self,tablename,data,restrication_str):
data_str = ''
for item in data.items():
data_str += '{}={},'.format(item[0],item[1])
values = data_str[:-1]
sql = 'update {} set {} where {}'.format(tablename,values,restrication_str)
print(sql)
try:
self.cursor.execute(sql)
self.conn.commit()
return self.cursor.rowcount
except Exception as e:
print(e)
self.conn.rollback()
def get_all(self,sql):
try:
self.cursor.execute(sql)
results = self.cursor.fetchall()
print(results)
return results
except Exception as e:
print(e)
return False
def get_one(self,sql):
try:
self.cursor.execute(sql)
results = self.cursor.fetchone()
print(results)
return results
except Exception as e:
print(e)
return False
def insert(self,tablename,data):
if len(data.keys()) == 1:
sql = 'insert into {}{} values'.format(tablename,data.keys[0]).replace("'",'') + '{}'.format(data.values()[0])
else:
sql = 'insert into {}{} values'.format(tablename,tuple(data.keys())).replace("'",'') + str('{}').format(tuple(data.values()))
try:
self.cursor.execute(sql)
self.conn.commit()
return int(self.cursor.lastrowid)
except Exception as e:
self.conn.rollback()
print(e)
return False
def delete(self,tableName,restrication_str):
sql = 'DELETE FROM {} WHERE {}'.format(tableName,restrication_str)
try:
self.cursor.execute(sql)
self.conn.commit()
return int(self.cursor.lastrowid)
except Exception as e:
self.conn.rollback()
print(e)
return False
def delete_table(self,tablename):
sql = 'DROP TABLE {} ;'.format(tablename)
try:
self.cursor.execute(sql)
self.conn.commit()
return int(self.cursor.lastrowid)
except Exception as e:
self.conn.rollback()
print(e)
return False
def foramt_tab(self,tablename):
sql = 'trncate table {}'.format(tablename)
try:
self.cursor.execute(sql)
self.conn.commit()
return int(self.cursor.lastrowid)
except Exception as e:
self.conn.rollback()
print(e)
return False
def query(self,sql):
try:
self.cursor.execute(sql)
self.conn.commit()
return int(self.cursor.lastrowid)
except Exception as e:
print(e)
self.conn.rollback()
return False
from mysqldemo.MySqlAPI_demo import MysqlDemo
mysql = MysqlDemo('host','username','passwd','dbname')