python pymysql库操作mysql数据库
- # coding=utf-8
-
- import pymysql
-
- def gettime():
- # 打开数据库连接
- db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi',charset='utf8')
-
- # 使用 cursor() 方法创建一个游标对象 cursor
- cursor = db.cursor()
-
- # 使用 execute() 方法执行 SQL 查询
- cursor.execute("SELECT now()")
-
- # 使用 fetchone() 方法获取单条数据.
- data = cursor.fetchone()
-
- print("当前时间: %s" % data)
-
- # 关闭指针对象
- cursor.close()
-
- # 关闭数据库连接
- db.close()
-
- def insert():
- # 打开数据库连接
- db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi')
-
- # 使用cursor()方法获取操作游标
- cursor = db.cursor()
-
- # SQL 插入语句
- sql = """INSERT INTO EMPLOYEE(FIRST_NAME,LAST_NAME, AGE, SEX, INCOME)
- VALUES ('Mac', 'Mohan', 20, 'M', 2000)"""
- try:
- # 执行sql语句
- cursor.execute(sql)
- # 提交到数据库执行
- db.commit()
- except:
- # 如果发生错误则回滚
- db.rollback()
-
- # 关闭指针对象
- cursor.close()
-
- # 关闭数据库连接
- db.close()
-
- def query():
- # 打开数据库连接
- db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi')
-
- # 使用cursor()方法获取操作游标
- #cursor = db.cursor()
-
- # 设置游标类型,默认游标类型为元组形式
- # 将游标类型设置为字典形式
- cursor = db.cursor(cursor=pymysql.cursors.DictCursor)
-
- # SQL 查询语句
- sql = "SELECT * FROM EMPLOYEE"
- try:
- # 执行SQL语句
- cursor.execute(sql)
- # 获取所有记录列表
- results = cursor.fetchall()
- print(results)
-
- # 游标类型为元组时的遍历方式
- # data_dict = []
- # for row in results:
- # i = 0
- # for field in cursor.description:
- # record = {}
- # rowname = field[0]
- # rowvalue = row[i]
- # record[rowname] = rowvalue
- # data_dict.append(record)
- # i += 1
- # print(data_dict)
- except:
- print ("Error: unable to fetch data")
-
- # 关闭指针对象
- cursor.close()
-
- # 关闭数据库连接
- db.close()
-
- def update():
- # 打开数据库连接
- db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi')
-
- # 使用cursor()方法获取操作游标
- cursor = db.cursor()
-
- # SQL 更新语句
- sql = "UPDATE EMPLOYEE SET AGE = AGE + 1"
-
- try:
- # 执行SQL语句
- cursor.execute(sql)
- # 提交到数据库执行
- db.commit()
- except:
- # 发生错误时回滚
- db.rollback()
-
- # 关闭指针对象
- cursor.close()
-
- # 关闭数据库连接
- db.close()
-
- def delete():
- # 打开数据库连接
- db = pymysql.connect(host='127.0.0.1',port=3306,user='root',passwd='clear1234',db='yuxi')
-
- # 使用cursor()方法获取操作游标
- cursor = db.cursor()
-
- # SQL 删除语句
- sql = "DELETE FROM EMPLOYEE WHERE FIRST_NAME = 'Mac1'"
- try:
- # 执行SQL语句
- cursor.execute(sql)
- # 提交修改
- db.commit()
- except:
- # 发生错误时回滚
- db.rollback()
-
- # 关闭指针对象
- cursor.close()
-
- # 关闭连接
- db.close()
-
- if __name__ == "__main__":
- gettime()
- #insert()
- #update()
- #delete()
- query()