Python3-pymysql模块-数据库操作之MySQL
博客转载
http://www.cnblogs.com/alex3714/articles/5950372.html
代码示例
import pymysql conn = None cursor = None try: # 连接数据库 conn = pymysql.connect(host='13.13.13.123', port=3306, user='root', passwd='******', db='db_name') # 获取游标对象 cursor = conn.cursor() # 执行insert语句 sql = "insert into tab_student(name,age,sex) values(%s,%s,%s)" sql_args = ("Joey1", 47, 1) row_count = cursor.execute(sql, sql_args) print(row_count) # 受影响的行数 # 执行多个insert语句 sql = "insert into tab_student(name,age,sex) values(%s,%s,%s)" sql_args = [("Joey2", 47, 1), ("Joey3", 47, 1), ("Joey4", 47, 1), ("Joey5", 47, 1), ] row_count = cursor.executemany(sql, sql_args) print(row_count) # 受影响的行数 # 提交事务 conn.commit() except Exception as ex: conn.rollback() finally: # 关闭游标与数据库连接 cursor.close() conn.close()
import pymysql conn = None cursor = None try: # 连接数据库 conn = pymysql.connect(host='13.13.13.123', port=3306, user='username', passwd='password', db='db_name') # 获取游标对象 cursor = conn.cursor() # 执行delete语句 sql = "delete from tab_student where name = %s and age = %s " sql_args = ("Joey", 47,) row_count = cursor.execute(sql, sql_args) print(row_count) # 受影响的行数 # 提交事务 conn.commit() except Exception as ex: conn.rollback() finally: # 关闭游标与数据库连接 cursor.close() conn.close()
import pymysql conn = None cursor = None try: # 连接数据库 conn = pymysql.connect(host='13.13.13.123', port=3306, user='username', passwd='password', db='db_name') # 获取游标对象 cursor = conn.cursor() # 执行update语句 sql = "update tab_student set name = %s where name like %s " sql_args = ("Jet", "J%",) row_count = cursor.execute(sql, sql_args) print(row_count) # 受影响的行数 # 提交事务 conn.commit() except Exception as ex: conn.rollback() finally: # 关闭游标与数据库连接 cursor.close() conn.close()
import pymysql conn = None cursor = None try: # 连接数据库 conn = pymysql.connect(host='13.13.13.123', port=3306, user='username', passwd='password', db='db_name') # 获取游标对象 cursor = conn.cursor() # 执行update语句 sql = "select * from tab_student where name = %s " sql_args = ("Jet", ) row_count = cursor.execute(sql, sql_args) print(row_count) # 查询结果的行数 # 获取查询结果 result = cursor.fetchone() # 提取一行查询结果 # result = cursor.fetchall() # 提取全部查询结果 # result = cursor.fetchmany(3) # 提取指定行的查询结果 print(result) except Exception as ex: conn.rollback() finally: # 关闭游标与数据库连接 cursor.close() conn.close()
posted on 2017-04-25 16:05 AustralGeek 阅读(191) 评论(0) 编辑 收藏 举报