Home  >  Article  >  Backend Development  >  Introducing the simple method of operating Mysql database in Python3.6

Introducing the simple method of operating Mysql database in Python3.6

巴扎黑
巴扎黑Original
2017-09-13 09:51:191870browse

This article mainly introduces the simple operation of Mysql database with Python3.6 in detail. It has certain reference value. Interested friends can refer to it.

This article shares the operation of Python3.6 with everyone. Specific examples of Mysql database are for your reference. The specific content is as follows

Install pymysql

Reference https://github.com/PyMySQL/PyMySQL/


pip install pymsql

Example one


##

import pymysql

# 创建连接
# 参数依次对应服务器地址,用户名,密码,数据库
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo')

# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)

# 执行语句返回影响的行数
effect_row = cursor.execute("select * from course")
print(effect_row)
# 获取所有数据
result = cursor.fetchall()
result = cursor.fetchone() # 获取下一个数据
result = cursor.fetchone() # 获取下一个数据(在上一个的基础之上)
# cursor.scroll(-1, mode='relative') # 相对位置移动
# cursor.scroll(0,mode='absolute') # 绝对位置移动

# 提交,不然无法保存新建或者修改的数据
conn.commit()
# 关闭游标
cursor.close()
# 关闭连接
conn.close()

Example two


import pymysql
# 建立连接
conn = pymysql.connect(host='127.0.0.1', user='root', passwd='123456', db='demo')
# 创建游标
cursor = conn.cursor(cursor=pymysql.cursors.DictCursor)
# 插入一条数据 %s是占位符 占位符之间用逗号隔开
effect_row = cursor.execute("insert into course(cou_name,time) values(%s,%s)", ("Engilsh", 100))
print(effect_row)
conn.commit()
cursor.close()

conn.close()

Example 3


import pymysql.cursors

# Connect to the database
connection = pymysql.connect(host='localhost',
        user='user',
        password='passwd',
        db='db',
        charset='utf8mb4',
        cursorclass=pymysql.cursors.DictCursor)

try:
 with connection.cursor() as cursor:
  # Create a new record
  sql = "INSERT INTO `users` (`email`, `password`) VALUES (%s, %s)"
  cursor.execute(sql, ('webmaster@python.org', 'very-secret'))

 # connection is not autocommit by default. So you must commit to save
 # your changes.
 connection.commit()

 with connection.cursor() as cursor:
  # Read a single record
  sql = "SELECT `id`, `password` FROM `users` WHERE `email`=%s"
  cursor.execute(sql, ('webmaster@python.org',))
  result = cursor.fetchone()
  print(result)
finally:
 connection.close()

The above is the detailed content of Introducing the simple method of operating Mysql database in Python3.6. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn