1、安装MySQL驱动
pip install mysql-connector
Python 3.6.7 (default, Oct 22 2018, 11:32:17) [GCC 8.2.0] on linuxType "help", "copyright", "credits" or "license" for more information.>>> import mysql.connector>>>
2、安装MySQL
MySQL安装请参考:https://www.cnblogs.com/webDepOfQWS/p/10685617.html
3、操作数据库
MySQL操作数据库的一般步骤如下:
a、建立连接 b、通过连接对象得到游标对象 c、执行SQL语句,获取执行结果,如果执行的SQL语句会改变数据库或表 ,需要提交,才会保存修改。 d、关闭游标对象,关闭连接对象。创建表并插入数据
在rms数据库中创建一张表:user_info并插入2条数据,创建表SQL语句如下:
create table user_info( id int(10) primary key, name char(20) not null, passwd char(40) not null, email char(20) not null, phone char(20) not null, role char(10) not null, sex char(10) not null, status int(10) not null, createAt datetime not null, exprAt datetime not null, validDays int(10) not null, delAt datetime )ENGINE=InnoDB DEFAULT CHARSET=utf8;
Python3代码:
#coding:utf-8#导入驱动import mysql.connector#建立连接conn = mysql.connector.connect(host="127.0.0.1",user='root',database='rms',password='password')#获游标标对象cursor = conn.cursor()#SQL语句SQL1='''create table user_info( id int(10) primary key, name char(20) not null, passwd char(40) not null, email char(20) not null, phone char(20) not null, role char(10) not null, sex char(10) not null, status int(10) not null, createAt datetime not null, exprAt datetime not null, validDays int(10) not null, delAt datetime )ENGINE=InnoDB DEFAULT CHARSET=utf8;'''SQL2='''insert into user_info values (1,"StephenWang7","123456","123@qq.com","15103887470","admin","male","200","20190412201130","20190419201130",30,null)'''try: #执行创建表的SQL语句 cursor.execute(SQL1) #执行插入语句 cursor.execute(SQL2) #提交 conn.commit()except Exception as e: print(e)finally: #关闭游标对象 cursor.close() #关闭连接 conn.close
连接数据库查看结果:
mysql> select count(*) from user_info;+----------+| count(*) |+----------+| 2 |+----------+1 row in set (0.27 sec)mysql>
查询SQL执行结果
fetchone():返回一条结果。
fetchall():返回所有结果。 fetchmany([size]):返回size条结果。 示例1:try: cursor.execute("select count(*) from user_info;") #获取执行结果 result = cursor.fetchone() print(result)except Exception as e: print(e)
输出1:
#返回的是一个tuple(2,)
示例2:
查询user_info表中所有的记录。try: cursor.execute("select count(*) from user_info;") #获取执行结果,fatchone 只返回一条结果 result = cursor.fetchone() print(result)except Exception as e: print(e)
运行示例2的代码时,报错:Unread result found,在连接数据库时设置'buffered': True。
conn = mysql.connector.connect(host="127.0.0.1",user='root',database='rms',password='password',buffered=True)
输出2:
(1, 'StephenWang7', '123456', '123@qq.com', '15103887470', 'admin', 'male', 200, datetime.datetime(2019, 4, 12, 20, 11, 30), datetime.datetime(2019, 4, 19, 20, 11, 30), 30, None)
更新和删除
更新和删除的代码与创建表类似,需要说明的一点是执行语句之后需要提交(commmit)。
#coding:utf-8#导入驱动import mysql.connector#建立连接conn = mysql.connector.connect(host="127.0.0.1",user='root',database='rms',password='password',buffered=True)#获游标标对象cursor = conn.cursor()try: #执行更新语句 cursor.execute("update user_info set passwd=%s where id=%s",['py123456',1]) #获取执行结果 result = cursor.fetchone() print(result) #提交 conn.commit()except Exception as e: print(e)finally: #关闭游标对象 cursor.close() #关闭连接 conn.close
MySQL的占位符为%s,连接数据库查看结果:
mysql> select passwd from user_info where id=1;+----------+| passwd |+----------+| py123456 |+----------+1 row in set (0.03 sec)