操作数据库,增删改查

接下来使用python转换成对应的代码查询

import pymysql

# 打开数据库连接
db = pymysql.connect(host='47.104.x.x',
                     port=3306, user='root', passwd='123456', db='test') # 使用 cursor() 方法创建一个游标对象cur cur = db.cursor() # 使用 execute() 方法执行 SQL 查询 cur.execute("select name, psw from user") # 使用 fetchall() 方法获取查询结果 data = cur.fetchall() print(data) # 关闭数据库连接 db.close()

运行结果:

(('yoyo_1', '111111'), ('yoyo', '123456'), ('yoyo_2', '111111'), ('yoyo_3', '222222'), ('yoyo_4', '444444'))

有时候我们只想查询某个字段对应的值,比如查询yoyo_1账号对应的psw值,并且取出来

select psw from user where name='yoyo_1'

查询的结果是(('111111',),) 元组嵌套元组,取值的话用下标取出来就可以了

import pymysql

def select_db(sql): '''查询数据库''' # 打开数据库连接 db = pymysql.connect(host='47.104.x.x', port=3306, user='root', passwd='123456', db='test') # 使用 cursor() 方法创建一个游标对象cur cur = db.cursor() # 使用 execute() 方法执行 SQL 查询 cur.execute(sql) # 使用 fetchall() 方法获取查询结果 data = cur.fetchall() # print(data) # 取出对应的psw值 # 关闭数据库连接 db.close() return data if __name__ == "__main__": sql = "select psw from user where name='yoyo_3'" a = select_db(sql)[0][0] print("查询结果:%s" %str(a))

删除操作

使用python删除一条数据,比如我要删除yoyo_1这条记录

delete from user where name='yoyo_1'

import pymysql


def delete_db(sql_delete): '''删除操作''' # 打开数据库连接 db = pymysql.connect(host='47.104.x.x', port=3306, user='root', passwd='123456', db='test') # 使用cursor()方法获取操作游标 cur = db.cursor() try: cur.execute(sql_delete) # 执行 # 提交 db.commit() except Exception as e: print("操作异常:%s" % str(e)) # 错误回滚 db.rollback() finally: db.close() if __name__ == '__main__': sql_delete ="delete from user where name='yoyo_1' " delete_db(sql_delete)

更新操作

更新name用户名是yoyo的用户,把psw改成666666

update user set psw='666666' where name='yoyo'

import pymysql


def update_db(sql_update): '''3.更新操作''' db = pymysql.connect(host='47.104.x.x', port=3306, user='root', passwd='123456', db='test') # 使用cursor()方法获取操作游标 cur = db.cursor() try: cur.execute(sql_update) # 执行sql # 提交 db.commit() except Exception as e: # 错误回滚 print("错误信息:%s" % str(e)) db.rollback() finally: db.close() if __name__ == '__main__': sql_update ="update user set psw='666666' where name='yoyo'" update_db(sql_update)

新增数据

往数据库里面插入一条数据,比如在user表里面新增一个用户信息yoyo_10,123456

insert into user(id, name, psw) values(10, 'yoyo_10', '123456')

import pymysql


def insert_db(sql_insert): '''插入操作''' db = pymysql.connect(host='47.104.x.x', port=3306, user='root', passwd='123456', db='test') # 使用cursor()方法获取操作游标 cur = db.cursor() try: cur.execute(sql_insert) # 提交 db.commit() except Exception as e: print("错误信息:%s" % str(e)) # 错误回滚 db.rollback() finally: db.close() if __name__ == "__main__": sql_insert = "insert into user(id, name, psw) values(10, 'yoyo_10', '123456')" insert_db(sql_insert)

从上面的代码可以看出,除了查询的代码不一样,新增、删除、更新数据库操作代码都一样,只是执行的sql不一样

猜你喜欢

转载自www.cnblogs.com/yaohu/p/10315744.html