python数据链接mysql数据库,增删改查

mac2024-03-14  25

python数据链接mysql数据库,增删改查

import MySQLdb def read(): # 打开数据库连接 db = MySQLdb.connect("localhost", "root", "", "test", charset='utf8' ) # 使用cursor()方法获取操作游标 cursor = db.cursor() # 使用execute方法执行SQL语句 try: cursor.execute("SELECT * from test1") # 使用 fetchone() 方法获取一条数据 #data = cursor.fetchone() data = cursor.fetchall() for i in data: print(i) # 关闭数据库连接 except: # Rollback in case there is any error db.rollback() db.close() def add(): # 打开数据库连接 db = MySQLdb.connect("localhost", "root", "", "test", charset='utf8' ) # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 插入语句 sql = 'INSERT INTO test1(`姓名`) VALUES ("Mohan")' try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # Rollback in case there is any error db.rollback() # 关闭数据库连接 db.close() def dele(): # 打开数据库连接 db = MySQLdb.connect("localhost", "root", "", "test", charset='utf8' ) # 使用cursor()方法获取操作游标 cursor = db.cursor() # SQL 删除语句 sql = 'DELETE FROM test1 WHERE `测试`>3' try: # 执行sql语句 cursor.execute(sql) # 提交到数据库执行 db.commit() except: # Rollback in case there is any error db.rollback() # 关闭数据库连接 db.close() for i in range(10): add()
最新回复(0)