9 与python2交互
1.创建外键

# 创建room表
mysql> create table rooms(id int primary key not null,title varchar());
Query OK, rows affected (0.01 sec) #创建学生表
mysql> create table stu(
-> id int primary key auto_increment not null,
-> name varchar(),
-> roomid int); #添加外键
mysql> alter table stu add constraint stu_room foreign key(roomid) references rooms(id); #添加数据
mysql> insert into stu values(,'郭靖',);
ERROR (): Cannot add or update a child row: a foreign key constraint fails (`py31`.`stu`, CONSTRAINT `stu_room` FOREIGN KEY (`roomid`) REFERENCES `rooms` (`id`)) mysql> insert into rooms values(,'聚义堂');
2. python2安装引入模块
python@ubuntu:~$ sudo apt-get install python-mysql #包名错误
正在读取软件包列表... 完成
正在分析软件包的依赖关系树
正在读取状态信息... 完成
E: 无法定位软件包 python-mysql
#安装mysql模块
python@ubuntu:~$ sudo apt-get install python-mysqldb
正在读取软件包列表... 完成
正在分析软件包的依赖关系树
正在读取状态信息... 完成
python-mysqldb 已经是最新版 (1.3.7-1build2)。
下列软件包是自动安装的并且现在不需要了:
linux-headers-4.4.0-22 linux-headers-4.4.0-22-generic linux-image-4.4.0-22-generic
linux-image-extra-4.4.0-22-generic
使用'sudo apt autoremove'来卸载它(它们)。
升级了 0 个软件包,新安装了 0 个软件包,要卸载 0 个软件包,有 395 个软件包未被升级。
- 在文件中引入模块
import Mysqldb
3.交互类型
(1)Connection对象
- 用于建立与数据库的连接
- 创建对象:调用connect()方法
conn=connect(参数列表)
- 参数host:连接的mysql主机,如果本机是'localhost'
- 参数port:连接的mysql主机的端口,默认是3306
- 参数db:数据库的名称
- 参数user:连接的用户名
- 参数password:连接的密码
- 参数charset:通信采用的编码方式,默认是'gb2312',要求与数据库创建时指定的编码一致,否则中文会乱码
对象的方法
- close()关闭连接
- commit()事务,所以需要提交才会生效
- rollback()事务,放弃之前的操作
- cursor()返回Cursor对象,用于执行sql语句并获得结果
(2)Cursor对象
- 执行sql语句
- 创建对象:调用Connection对象的cursor()方法
cursor1=conn.cursor()
对象的方法
- close()关闭
- execute(operation [, parameters ])执行语句,返回受影响的行数
- fetchone()执行查询语句时,获取查询结果集的第一个行数据,返回一个元组
- next()执行查询语句时,获取当前行的下一行
- fetchall()执行查询时,获取结果集的所有行,一行构成一个元组,再将这些元组装入一个元组返回
- scroll(value[,mode])将行指针移动到某个位置
- mode表示移动的方式
- mode的默认值为relative,表示基于当前行移动到value,value为正则向下移动,value为负则向上移动
- mode的值为absolute,表示基于第一条数据的位置,第一条数据的位置为0
对象的属性
- rowcount只读属性,表示最近一次execute()执行后受影响的行数
- connection获得当前连接对象
4.增删改查
(1)增加
# -*- coding :utf-8 -*- from MySQLdb import * #导入包 try:
conn = connect(host="localhost", port=3306, user="root", passwd="mysql", db="py31", charset="utf8") #Connection对象
cursor1 = conn.cursor() #Cursor对象 sql = 'insert into students(name) values("alex")' #sql语句
cursor1.execute(sql) #执行 conn.commit() #提交 cursor1.close()
conn.close() #关闭
except Exception as e:
print(e.message)
| 13 | alex | | NULL | |
+----+-----------+--------+---------------------+----------+
(2)修改数据
sql = 'update students set name="jack" where id=10'
(3)删除数据
sql = 'delete from students where id=9'
5.sql语句参数化
用户输入:a'or 1=1 or'
分号会影响sql语句
select * from students where name=@name
(1)参数化
# -*- coding:utf-8 -*- from MySQLdb import * try:
conn = connect(host="localhost", port=3306, user="root", passwd="mysql", db="py31", charset="utf8")
cursor1 = conn.cursor() name = raw_input("请输入名字:")
p_name = [name] #sql = 'insert into students(name) values(%s)'%p_name
#cursor1.execute()
cursor1.execute('insert into students(name) values(%s)',p_name) conn.commit() cursor1.close()
conn.close()
print("----ok---") except Exception as e:
print(e.message)
| 15 | 'lala'haha | | NULL | |
+----+------------+--------+---------------------+----------+
(2) 列表作为参数
# -*- coding:utf-8 -*- from MySQLdb import * try:
name = raw_input("请输入名字:")
conn = connect(host="localhost", port=3306, user="root", passwd="mysql", db="py31", charset="utf8")
cursor1 = conn.cursor() sql = 'insert into students(name) values(%s)' cursor1.execute(sql,[name])
conn.commit() cursor1.close()
conn.close()
print("----ok---") except Exception as e:
print(e.message)
6.查询
(1)查询一条学生信息
# -*- coding:utf-8 -*- from MySQLdb import * try:
#name = raw_input("请输入名字:")
conn = connect(host="localhost", port=3306, user="root", passwd="mysql", db="py31", charset="utf8")
cursor1 = conn.cursor() #sql = 'insert into students(name) values("alex")'
#sql = 'update students set name="jack" where id=10'
#sql = 'delete from students where id=9' #sql = 'insert into students(name) values(%s)'
#cursor1.execute(sql,[name]) sql = 'select * from students where id=4'
cursor1.execute(sql) result = cursor1.fetchone()
print(result) cursor1.close()
conn.close()
print("----ok---") except Exception as e:
print(e.message)
(4L, u'\u5c0f\u7c73', '\x01', None, '\x00')
----ok---
(2)查询多行数据
# -*- coding:utf-8 -*- from MySQLdb import * try:
#name = raw_input("请输入名字:")
conn = connect(host="localhost", port=3306, user="root", passwd="mysql", db="py31", charset="utf8")
cursor1 = conn.cursor() #sql = 'insert into students(name) values("alex")'
#sql = 'update students set name="jack" where id=10'
#sql = 'delete from students where id=9' #sql = 'insert into students(name) values(%s)'
#cursor1.execute(sql,[name]) sql = 'select * from students'
cursor1.execute(sql) result = cursor1.fetchall()
print(result) cursor1.close()
conn.close()
print("----ok---") except Exception as e:
print(e.message)
((1L, u'\u5c0f\u90ed', '\x01', datetime.datetime(1999, 9, 9, 0, 0), '\x00'), (2L, u'\u817e\u65ed', '\x01', datetime.datetime(1990, 2, 2, 0, 0), '\x00'), (3L, u'\u7f51\u6613', '\x01', None, '\x00'), (4L, u'\u5c0f\u7c73', '\x01', None, '\x00'), (6L, u'\u9177\u72d7', '\x00', datetime.datetime(2017, 2, 13, 0, 0), '\x01'), (7L, u'QQ', '\x01', None, '\x00'), (8L, u'\u817e\u8baf\u4e91', '\x01', None, '\x00'), (10L, u'jack', '\x01', None, '\x00'), (11L, u'\u5fae\u535a', '\x01', None, '\x00'), (12L, u'\u5fae\u4fe1', '\x01', None, '\x00'), (13L, u'alex', '\x01', None, '\x00'), (14L, u'lalal', '\x01', None, '\x00'), (15L, u"'lala'haha", '\x01', None, '\x00'), (16L, u"''tae", '\x01', None, '\x00'))
----ok---
(3) 格式化输出数据
# 执行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 )
9 与python2交互的更多相关文章
- python2.7入门---文件I/O&简单用户交互
这篇文章开始之前,我们先来看下python中的输出方法.最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式.此函数把你传递的表达式转换成一个字符串表达式,并将结果写 ...
- Centos启动Cassandra交互模式失败:No appropriate python interpreter found
在CentOS6.5安装好Cassandra后,启动交互模式: bin/sqlsh 192.168.10.154 时,报错 No appropriate python interpreter foun ...
- Python2.7.12开发环境构建(自动补全)
一.安装readline-devel包 Python的编译安装依赖于这个包 yum -y install readline-devel 二.安装Python2.7.12 Python官方网站(到此处下 ...
- Python2.4-原理之函数
此节来自于<Python学习手册第四版>第四部分 一.函数基础 函数的作用在每个编程语言中都是大同小异的,,这个表是函数的相关语句和表达式. 1.编写函数,a.def是可执行代码,pyth ...
- Python2.6-原理之类和oop(下)
来自<python学习手册第四版>第六部分 五.运算符重载(29章) 这部分深入介绍更多的细节并看一些常用的重载方法,虽然不会展示每种可用的运算符重载方法,但是这里给出的代码也足够覆盖py ...
- Python2.x和3.x主要差异总结
本文部分转载自http://my.oschina.net/chihz/blog/123437,部分来自自身修改 开始使用Python之后就到处宣扬Python如何如何好,宣传工作的一大重要诀窍就是做对 ...
- Python(文件、文件夹压缩处理模块,shelve持久化模块,xml处理模块、ConfigParser文档配置模块、hashlib加密模块,subprocess系统交互模块 log模块)
OS模块 提供对操作系统进行调用的接口 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname") 改变当前脚本工作目 ...
- Python2和Python3在windows下共存
Python2.7 和 Python3不兼容,两种环境可能都会用到.ubuntu14.04中已经默认安装了这两个版本,在shell中输入python会自动进入Python2.7的交互环境,输入Pyth ...
- 4.python中的用户交互
学习完如何写'hello world'之后,我们还是不太满意,因为这样代码就写死了,以后运行的时候都只打印一局固定的话而已. 但是,我想在程序运行后,自己手动输入内容怎么办,此时就要学习如何使用用户交 ...
随机推荐
- Bonita portal 源码编译(未完成)
首先下载源代码 https://github.com/bonitasoft/bonita-portal-js 以下内容为Github 的安装教程包含我安装过程中遇到的问题.并加以修正 Bonita p ...
- May 2 2017 Week 18 Tuesday
The beauty of the journey is found in the scenery along the way. 旅行之美在于沿途所见的风景. Several years ago, I ...
- 了解Web及网络基础(二)
HTTP报文分为两种,HTTP请求报文跟HTTP响应报文. HTTP请求报文的结构如下: 其中,请求行中包括的内容有方法.URI和HTTP版本,请求首部字段.通用首部字段和实体首部字段隶属于HTTP首 ...
- HashMap通过hashcode对其内容进行快速查找,而 TreeMap中所有的元素都保持着某种固定的顺序
HashMap通过hashcode对其内容进行快速查找,而 TreeMap中所有的元素都保持着某种固定的顺序,如果你需要得到一个有序的结果你就应该使用TreeMap(HashMap中元素的排列顺序是不 ...
- Centos 5.2下安装多个mysql数据库
一.编译安装第一个MySQL 5.1.33 cd /opt/usr/sbin/groupadd mysql/usr/sbin/useradd -g mysql mysql -s /bin/nologi ...
- CTS、CLS、CLR分别作何解释?
CTS.CLS.CLR分别作何解释? 答:CTS:通用类型系统.CLS:通用语言规范.CLR:公共语言运行库.
- mac系统的几种u盘启动制作方式
先拿一个U盘,格式化好(guid分区表之类的选项弄好) 1.通过终端制作: 1>下载好自己要安装的系统镜像,最新的在App Store上下,以前的可以去pc 苹果等地方下载 2>在终端输入 ...
- 实战 Lucene2.0
Lucene 简介 Lucene 是一个基于 Java 的全文信息检索工具包,它不是一个完整的搜索应用程序,而是为你的应用程序提供索引和搜索功能.Lucene 目前是 Apache Jakarta 家 ...
- MySQL超大表如何提高count速度
经常用到count统计记录数,表又超级大,这时候sql执行很慢,就是走索引,也是很慢的,怎么办呢? 1.这个时候我们就要想为什么这么慢:根本原因是访问的数据量太大,就算只计算记录数也是很慢的. 2.如 ...
- uplift model学习笔记
一.解决的问题: 通常的 Propensity Model 和 Response Model 只是给目标用户打了个分,并没有确保模型的结果可以使得活动的提升最大化:它没有告诉市场营销人员,哪个用户最有 ...