python对数据库mysql的操作(增删改查)

Posted fengzixian

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python对数据库mysql的操作(增删改查)相关的知识,希望对你有一定的参考价值。

#coding=utf-8

import pymysql

# #查询
# def connMySQL():
# try:
# conn=pymysql.connect(‘localhost‘,‘root‘,‘admin‘)
# conn.select_db(‘five‘)
# except Exception as e:
# return e.args
# else:
# cur=conn.cursor()
# cur.execute("select * from users")
# data=cur.fetchall()
# # for item in data:
# # print(item)
# #列表推导式
# db=[item for item in data]
# print(db)
# # 打开之后进行关闭,不然会占用资源
# finally:
# cur.close()
# conn.commit()
# conn.close()
#
# print(connMySQL())



# #插入数据
# def insertMySql():
# try:
# conn=pymysql.connect(‘localhost‘,‘root‘,‘admin‘)
# conn.select_db(‘five‘)
# except Exception as e:
# return e.args
# else:
# cur=conn.cursor()
# #单条插入
# # sql=‘insert into users values (%s,%s,%s,%s)‘
# # params=(12,‘wei‘,99,‘changjiang‘)
# #多条插入
# sql = ‘insert into users values (%s,%s,%s,%s)‘
# params=[(13,‘wei‘,99,‘changjiang‘),(14,‘wei‘,99,‘changjiang‘),(15,‘wei‘,99,‘changjiang‘)]
# cur.executemany(sql,params)
# conn.commit()
# # 打开之后进行关闭,不然会占用资源
# finally:
# cur.close()
# conn.close()
#
# insertMySql()

#插入数据

# #删除数据
# def deleteMySql():
# try:
# conn=pymysql.connect(‘localhost‘,‘root‘,‘admin‘)
# conn.select_db(‘five‘)
# except Exception as e:
# return e.args
# else:
# cur=conn.cursor()
# #多条插入
# cur.execute = ‘delete * from users where id= 1‘
# conn.commit()
# # 打开之后进行关闭,不然会占用资源
# finally:
# cur.close()
# conn.close()
#
# deleteMySql()


class MySqlHelper:
def conn(self):
con=pymysql.connect(
host=‘127.0.0.1‘,
user=‘root‘,
passwd=‘admin‘,
db=‘aimin‘)
return con

def get_one(self,sql,params):
cur=self.conn().cursor()
data=cur.execute(sql,params)
result=cur.fetchone()
return result

def checkValid(username,password):
opera=MySqlHelper()
sql=‘select * from login where username=%s and password=%s‘
params=(username,password)
return opera.get_one(sql=sql,params=params)

def info():
username=input(‘请输入用户名: ‘)
password=input(‘请输入密码: ‘)
result=checkValid(username,password)
if result:
print(‘登录成功,昵称:{0}‘.format(username))
else:
print(‘失败‘)

if __name__==‘__main__‘:
info()

以上是关于python对数据库mysql的操作(增删改查)的主要内容,如果未能解决你的问题,请参考以下文章

python操作mysql--增删改查

python操作mysql之增删改查

python操作mysql数据库实现增删改查

python操作mysql数据库实现增删改查

Python 之 增删改查Mysql数据库

MySQL数据库使用pymysql对数据库进行增删改查