“Python操作MySQL数据库”的版本间的差异

来自CloudWiki
跳转至: 导航搜索
安装PyMySQL
数据库查询操作
 
(未显示2个用户的10个中间版本)
第3行: 第3行:
 
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
 
PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。
 
在命令行中使用:
 
在命令行中使用:
  pip3 install PyMySQL
+
  pip3 install pymysql
  
===数据库连接===
+
===建立数据库===
接下来我们在 MySQL 中创建 cloud 数据库,并创建 user 数据表,表结构如下:
+
C:\Users\maxin>mysql -uroot -p
  <nowiki>mysql> create database cloud;
+
 
   
+
  <nowiki>Enter password: ******
Query OK, 1 row affected (0.00 sec)
+
Welcome to the MySQL monitor.  Commands end with ; or \g.
 +
Your MySQL connection id is 4
 +
Server version: 5.7.29-log MySQL Community Server (GPL)
 +
 
 +
Copyright (c) 2000, 2021, Oracle and/or its affiliates.
 +
 
 +
Oracle is a registered trademark of Oracle Corporation and/or its
 +
affiliates. Other names may be trademarks of their respective
 +
owners.
 +
 
 +
Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.
  
mysql> use cloud;
+
mysql></nowiki>  
Database changed
 
mysql>  CREATE TABLE IF NOT EXISTS `user`(
 
  `id` INT UNSIGNED AUTO_INCREMENT,
 
  `name` VARCHAR(100) NOT NULL,
 
  `password` VARCHAR(40) NOT NULL,
 
  PRIMARY KEY ( `id` ) 
 
)ENGINE=InnoDB DEFAULT CHARSET=utf8;
 
mysql>  CREATE UNIQUE INDEX uname on user(name);
 
Query OK, 0 rows affected (0.25 sec)
 
Records: 0  Duplicates: 0  Warnings: 0
 
</nowiki>
 
  
插入一些数据:
+
CREATE DATABASE `notebook` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;
  
  <nowiki>mysql> INSERT INTO `user` (name,password) VALUES ('ma', '123456');
+
  Query OK, 1 row affected (0.00 sec)
Query OK, 1 row affected (0.12 sec)
 
  
mysql> INSERT INTO `user` (name,password) VALUES ('ma', '123457');
+
===数据库连接===
ERROR 1062 (23000): Duplicate entry 'ma' for key 2</nowiki>
 
  
</nowiki>
 
 
Python连接数据库代码:
 
Python连接数据库代码:
  <nowiki>import pymysql
+
  <nowiki>
+
import pymysql
 +
 
 +
host = '127.0.0.1'    # 主机名
 +
user = 'root'        # 数据库用户名
 +
password = '123456'    # 数据库密码
 +
database = 'notebook' # 数据库名称
 +
db = pymysql.connect(host=host,user=user,password=password,db=database) # 建立连接
 
# 打开数据库连接
 
# 打开数据库连接
db = pymysql.connect("localhost","testuser","test123","TESTDB" )
+
 
+
#这4个参数依次是:主机名,用户名,密码和数据库名
 
# 使用 cursor() 方法创建一个游标对象 cursor
 
# 使用 cursor() 方法创建一个游标对象 cursor
 
cursor = db.cursor()
 
cursor = db.cursor()
第53行: 第55行:
 
db.close()</nowiki>
 
db.close()</nowiki>
  
 +
执行以上脚本输出结果如下:
 +
Database version : 5.0.22-community-nt
 +
 +
===创建数据库表===
 +
<nowiki>
 +
import pymysql
 +
 +
host = '127.0.0.1'    # 主机名
 +
user = 'root'        # 数据库用户名
 +
password = '000000'    # 数据库密码
 +
database = 'notebook' # 数据库名称
 +
db = pymysql.connect(host=host,user=user,password=password,db=database) # 建立连接
 +
# 打开数据库连接
 +
 +
#这4个参数依次是:主机名,用户名,密码和数据库名
 +
# 使用 cursor() 方法创建一个游标对象 cursor
 +
cursor = db.cursor()
 +
 +
# 使用 execute() 方法执行 SQL,如果表存在则删除
 +
cursor.execute("DROP TABLE IF EXISTS users")
 +
 +
# 使用预处理语句创建表
 +
sql = """CREATE TABLE `users` (
 +
  `id` int(8) NOT NULL AUTO_INCREMENT,
 +
  `username` varchar(255) DEFAULT NULL,
 +
  `email` varchar(255) DEFAULT NULL,
 +
  `password` varchar(255) DEFAULT NULL,
 +
  PRIMARY KEY (`id`)
 +
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
 +
 +
cursor.execute(sql)
 +
 +
# 关闭数据库连接
 +
db.close()
 +
 +
</nowiki>
 +
 +
====终端验证====
 +
<nowiki>
 +
mysql> show databases;
 +
+--------------------+
 +
| Database          |
 +
+--------------------+
 +
| information_schema |
 +
| mysql              |
 +
| notebook          |
 +
| performance_schema |
 +
| sys                |
 +
+--------------------+
 +
5 rows in set (0.01 sec)
 +
 +
mysql> use notebook
 +
Database changed
 +
mysql> show tables
 +
    -> ;
 +
+--------------------+
 +
| Tables_in_notebook |
 +
+--------------------+
 +
| users              |
 +
+--------------------+
 +
1 row in set (0.00 sec)</nowiki>
 +
 +
===数据库插入操作===
 +
 +
====示例1====
 +
<nowiki>
 +
import pymysql
 +
 +
host = '127.0.0.1'    # 主机名
 +
user = 'root'        # 数据库用户名
 +
password = '000000'    # 数据库密码
 +
database = 'notebook' # 数据库名称
 +
db = pymysql.connect(host=host,user=user,password=password,db=database) # 建立连接
 +
# 打开数据库连接
 +
 +
#这4个参数依次是:主机名,用户名,密码和数据库名
 +
# 使用 cursor() 方法创建一个游标对象 cursor
 +
cursor = db.cursor()
 +
 +
email = 'maxin5@163.com'
 +
username = 'maxin5'
 +
password ='123456'
 +
# 使用预处理语句创建表
 +
 +
sql = "INSERT INTO users(username,email,password) VALUES ('%s', '%s', '%s')" % (email,username,password)
 +
 +
try:
 +
  # 执行sql语句
 +
  cursor.execute(sql)
 +
  # 执行sql语句
 +
  db.commit()
 +
except:
 +
  # 发生错误时回滚
 +
  db.rollback()
 +
 +
 +
# 关闭数据库连接
 +
db.close()</nowiki>
 +
 +
====示例2====
 +
<nowiki>import pymysql
 +
 +
# 打开数据库连接
 +
db = pymysql.connect("localhost","root","000000","cloud" )
 +
 +
# 使用cursor()方法获取操作游标
 +
cursor = db.cursor()
 +
 +
# SQL 插入语句
 +
sql = "INSERT INTO EMPLOYER(FIRST_NAME, \
 +
      LAST_NAME, AGE, SEX, INCOME) \
 +
      VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
 +
      ('Mac', 'Mohan', 20, 'M', 2000)
 +
#这里使用的是预编译用法,%s,%d,%c分别指代字符串、数字和字符
 +
try:
 +
  # 执行sql语句
 +
  cursor.execute(sql)
 +
  # 执行sql语句
 +
  db.commit()
 +
except:
 +
  # 发生错误时回滚
 +
  db.rollback()
 +
 +
# 关闭数据库连接
 +
db.close()
 +
</nowiki>
  
首先需要安装MySQLDb
+
===数据库查询操作===
  
http://trac.edgewall.org/wiki/MySqlDb
+
Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。
  
MySQLDb模块的主要方法:
+
*fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
*commit() :提交事务。
+
*fetchall(): 接收全部的返回结果行.
*rollback() :回滚事务。
+
*rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。
*callproc(self, procname, args):用来执行存储过程,接收的参数为存储过程名和参数列表,返回值为受影响的行数。
 
*execute(self, query, args):执行单条sql语句,接收的参数为sql语句本身和使用的参数列表,返回值为受影响的行数。
 
*executemany(self, query, args):执行单条sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数。
 
  
*nextset(self):移动到下一个结果集。
+
====实例1 ====
*fetchall(self):接收全部的返回结果行。
+
<nowiki>
*fetchmany(self, size=None):接收size条返回结果行,如果size的值大于返回的结果行的数量,则会返回cursor.arraysize条数据。
+
import pymysql
*fetchone(self):返回一条结果行。
 
*scroll(self, value, mode='relative'):移动指针到某一行。如果mode='relative'则表示从当前所在行移动value条,如果 mode='absolute'则表示从结果集的第一行移动value条。
 
  
 +
host = '127.0.0.1'    # 主机名
 +
user = 'root'        # 数据库用户名
 +
password = '000000'    # 数据库密码
 +
database = 'store' # 数据库名称
 +
db = pymysql.connect(host=host,user=user,password=password,db=database) # 建立连接
 +
# 打开数据库连接
  
===查询记录===
+
#这4个参数依次是:主机名,用户名,密码和数据库名
 +
# 使用 cursor() 方法创建一个游标对象 cursor
 +
cursor = db.cursor()
  
<nowiki>import MySQLdb
+
# SQL 查询语句
 +
sql = "SELECT * FROM users"
 
try:
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',db='test',port=3306)
+
  # 执行SQL语句
    cur=conn.cursor()
+
  cursor.execute(sql)
    cur.execute('select * from user')
+
  # 获取所有记录列表
    cur.close()
+
  results = cursor.fetchall()
    conn.close()
+
  for row in results:
except MySQLdb.Error,e:
+
      name=row[2]
    print("Mysql Error %d: %s" % (e.args[0], e.args[1]))</nowiki>
+
      email=row[1]
 +
      password=row[3]
 +
      # 打印结果
 +
      print ("name=%s,email=%s,password=%s" % \
 +
            (name, email,password))
 +
except:
 +
  print ("Error: unable to fetch data")
 +
 +
# 关闭数据库连接
 +
db.close()</nowiki>
  
 +
====实例2====
  
===插入数据===
+
查询EMPLOYEE表中salary(工资)字段大于1000的所有数据:
  
  <nowiki>import MySQLdb
+
  <nowiki>import pymysql
 +
 +
# 打开数据库连接
 +
db = pymysql.connect("localhost","root","000000","cloud" )
 +
 +
# 使用cursor()方法获取操作游标
 +
cursor = db.cursor()
 +
 +
# SQL 查询语句
 +
sql = "SELECT * FROM EMPLOYER \
 +
      WHERE INCOME > '%d'" % (1000)
 
try:
 
try:
    conn=MySQLdb.connect(host='localhost',user='root',passwd='root',port=3306)
+
  # 执行SQL语句
    cur=conn.cursor()
+
  cursor.execute(sql)
    cur.execute('create database if not exists python')
+
  # 获取所有记录列表
    conn.select_db('python')
+
  results = cursor.fetchall()
    cur.execute('create table test(id int,info varchar(20))')
+
  for row in results:
    value=[1,'hi rollen']
+
      fname = row[0]
    cur.execute('insert into test values(%s,%s)',value)
+
      lname = row[1]
    values=[]
+
      age = row[2]
    for i in range(20):
+
      sex = row[3]
        values.append((i,'hi rollen'+str(i)))
+
      income = row[4]
    cur.executemany('insert into test values(%s,%s)',values)
+
      # 打印结果
    cur.execute('update test set info="I am rollen" where id=3')
+
      print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
    conn.commit()
+
            (fname, lname, age, sex, income ))
    cur.close()
+
except:
    conn.close()
+
  print ("Error: unable to fetch data")
except MySQLdb.Error,e:
+
    print("Mysql Error %d: %s" % (e.args[0], e.args[1]))
+
# 关闭数据库连接
</nowiki>
+
db.close()</nowiki>
 +
 
 +
===数据库更新操作===
 +
 
 +
===数据库删除操作===
 +
 
 +
===执行事务===
 +
 
  
 
返回 [[文件和数据格式化(输入与输出)]]
 
返回 [[文件和数据格式化(输入与输出)]]

2022年1月26日 (三) 07:08的最新版本

操作MySQL数据库

安装PyMySQL

PyMySQL 是在 Python3.x 版本中用于连接 MySQL 服务器的一个库,Python2中则使用mysqldb。 在命令行中使用:

pip3 install pymysql

建立数据库

C:\Users\maxin>mysql -uroot -p

Enter password: ******
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 4
Server version: 5.7.29-log MySQL Community Server (GPL)

Copyright (c) 2000, 2021, Oracle and/or its affiliates.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> 

CREATE DATABASE `notebook` DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;

Query OK, 1 row affected (0.00 sec)

数据库连接

Python连接数据库代码:

import pymysql

host = '127.0.0.1'    # 主机名
user = 'root'         # 数据库用户名
password = '123456'     # 数据库密码
database = 'notebook' # 数据库名称
db = pymysql.connect(host=host,user=user,password=password,db=database) # 建立连接
# 打开数据库连接

#这4个参数依次是:主机名,用户名,密码和数据库名
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute()  方法执行 SQL 查询 
cursor.execute("SELECT VERSION()")
 
# 使用 fetchone() 方法获取单条数据.
data = cursor.fetchone()
 
print ("Database version : %s " % data)
 
# 关闭数据库连接
db.close()

执行以上脚本输出结果如下:

Database version : 5.0.22-community-nt

创建数据库表

import pymysql

host = '127.0.0.1'    # 主机名
user = 'root'         # 数据库用户名
password = '000000'     # 数据库密码
database = 'notebook' # 数据库名称
db = pymysql.connect(host=host,user=user,password=password,db=database) # 建立连接
# 打开数据库连接

#这4个参数依次是:主机名,用户名,密码和数据库名
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
# 使用 execute() 方法执行 SQL,如果表存在则删除
cursor.execute("DROP TABLE IF EXISTS users")
 
# 使用预处理语句创建表
sql = """CREATE TABLE `users` (
  `id` int(8) NOT NULL AUTO_INCREMENT,
  `username` varchar(255) DEFAULT NULL,
  `email` varchar(255) DEFAULT NULL,
  `password` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;"""
 
cursor.execute(sql)
 
# 关闭数据库连接
db.close()


终端验证

mysql> show databases;
+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| notebook           |
| performance_schema |
| sys                |
+--------------------+
5 rows in set (0.01 sec)

mysql> use notebook
Database changed
mysql> show tables
    -> ;
+--------------------+
| Tables_in_notebook |
+--------------------+
| users              |
+--------------------+
1 row in set (0.00 sec)

数据库插入操作

示例1

import pymysql

host = '127.0.0.1'    # 主机名
user = 'root'         # 数据库用户名
password = '000000'     # 数据库密码
database = 'notebook' # 数据库名称
db = pymysql.connect(host=host,user=user,password=password,db=database) # 建立连接
# 打开数据库连接

#这4个参数依次是:主机名,用户名,密码和数据库名
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()
 
email = 'maxin5@163.com'
username = 'maxin5'
password ='123456'
# 使用预处理语句创建表

sql = "INSERT INTO users(username,email,password) VALUES ('%s', '%s', '%s')" % (email,username,password)
 
try:
   # 执行sql语句
   cursor.execute(sql)
   # 执行sql语句
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
 
# 关闭数据库连接
db.close()

示例2

import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost","root","000000","cloud" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 插入语句
sql = "INSERT INTO EMPLOYER(FIRST_NAME, \
       LAST_NAME, AGE, SEX, INCOME) \
       VALUES ('%s', '%s', '%d', '%c', '%d' )" % \
       ('Mac', 'Mohan', 20, 'M', 2000)
#这里使用的是预编译用法,%s,%d,%c分别指代字符串、数字和字符
try:
   # 执行sql语句
   cursor.execute(sql)
   # 执行sql语句
   db.commit()
except:
   # 发生错误时回滚
   db.rollback()
 
# 关闭数据库连接
db.close()

数据库查询操作

Python查询Mysql使用 fetchone() 方法获取单条数据, 使用fetchall() 方法获取多条数据。

  • fetchone(): 该方法获取下一个查询结果集。结果集是一个对象
  • fetchall(): 接收全部的返回结果行.
  • rowcount: 这是一个只读属性,并返回执行execute()方法后影响的行数。

实例1

import pymysql

host = '127.0.0.1'    # 主机名
user = 'root'         # 数据库用户名
password = '000000'     # 数据库密码
database = 'store' # 数据库名称
db = pymysql.connect(host=host,user=user,password=password,db=database) # 建立连接
# 打开数据库连接

#这4个参数依次是:主机名,用户名,密码和数据库名
# 使用 cursor() 方法创建一个游标对象 cursor
cursor = db.cursor()

# SQL 查询语句
sql = "SELECT * FROM users"
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      name=row[2]
      email=row[1]
      password=row[3]
       # 打印结果
      print ("name=%s,email=%s,password=%s" % \
             (name, email,password))
except:
   print ("Error: unable to fetch data")
 
# 关闭数据库连接
db.close()

实例2

查询EMPLOYEE表中salary(工资)字段大于1000的所有数据:

import pymysql
 
# 打开数据库连接
db = pymysql.connect("localhost","root","000000","cloud" )
 
# 使用cursor()方法获取操作游标 
cursor = db.cursor()
 
# SQL 查询语句
sql = "SELECT * FROM EMPLOYER \
       WHERE INCOME > '%d'" % (1000)
try:
   # 执行SQL语句
   cursor.execute(sql)
   # 获取所有记录列表
   results = cursor.fetchall()
   for row in results:
      fname = row[0]
      lname = row[1]
      age = row[2]
      sex = row[3]
      income = row[4]
       # 打印结果
      print ("fname=%s,lname=%s,age=%d,sex=%s,income=%d" % \
             (fname, lname, age, sex, income ))
except:
   print ("Error: unable to fetch data")
 
# 关闭数据库连接
db.close()

数据库更新操作

数据库删除操作

执行事务

返回 文件和数据格式化(输入与输出)