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交互的更多相关文章

  1. python2.7入门---文件I/O&简单用户交互

        这篇文章开始之前,我们先来看下python中的输出方法.最简单的输出方法是用print语句,你可以给它传递零个或多个用逗号隔开的表达式.此函数把你传递的表达式转换成一个字符串表达式,并将结果写 ...

  2. Centos启动Cassandra交互模式失败:No appropriate python interpreter found

    在CentOS6.5安装好Cassandra后,启动交互模式: bin/sqlsh 192.168.10.154 时,报错 No appropriate python interpreter foun ...

  3. Python2.7.12开发环境构建(自动补全)

    一.安装readline-devel包 Python的编译安装依赖于这个包 yum -y install readline-devel 二.安装Python2.7.12 Python官方网站(到此处下 ...

  4. Python2.4-原理之函数

    此节来自于<Python学习手册第四版>第四部分 一.函数基础 函数的作用在每个编程语言中都是大同小异的,,这个表是函数的相关语句和表达式. 1.编写函数,a.def是可执行代码,pyth ...

  5. Python2.6-原理之类和oop(下)

    来自<python学习手册第四版>第六部分 五.运算符重载(29章) 这部分深入介绍更多的细节并看一些常用的重载方法,虽然不会展示每种可用的运算符重载方法,但是这里给出的代码也足够覆盖py ...

  6. Python2.x和3.x主要差异总结

    本文部分转载自http://my.oschina.net/chihz/blog/123437,部分来自自身修改 开始使用Python之后就到处宣扬Python如何如何好,宣传工作的一大重要诀窍就是做对 ...

  7. Python(文件、文件夹压缩处理模块,shelve持久化模块,xml处理模块、ConfigParser文档配置模块、hashlib加密模块,subprocess系统交互模块 log模块)

    OS模块 提供对操作系统进行调用的接口 os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径 os.chdir("dirname")  改变当前脚本工作目 ...

  8. Python2和Python3在windows下共存

    Python2.7 和 Python3不兼容,两种环境可能都会用到.ubuntu14.04中已经默认安装了这两个版本,在shell中输入python会自动进入Python2.7的交互环境,输入Pyth ...

  9. 4.python中的用户交互

    学习完如何写'hello world'之后,我们还是不太满意,因为这样代码就写死了,以后运行的时候都只打印一局固定的话而已. 但是,我想在程序运行后,自己手动输入内容怎么办,此时就要学习如何使用用户交 ...

随机推荐

  1. 【转】【MATLAB】模拟和数字低通滤波器的MATLAB实现

    原文地址:http://blog.sina.com.cn/s/blog_79ecf6980100vcrf.html 低通滤波器参数:Fs=8000,fp=2500,fs=3500,Rp=1dB,As= ...

  2. 关于Linux主流框架运维工作剖析

    LINUX是开源的,这也是最主要的原因,想学Windows,Unix对不起,没有源代码.也正是因为这样,LINUX才能够像雪球一样越滚越大,发展到现在这种规模.今天将为大家带来关于Linux主流框架运 ...

  3. window下编译ffmpeg

    网上关于编译ffmpeg的帖子很多,我也尝试了很多次,但是很多都过不了,一部分原因是版本问题,还有就是有的路劲没说的太明白导致的,经过一天的摸索,最终编译好了,下面把编译方式写下来,希望对看到帖子的人 ...

  4. 【JavaScript 封装库】Prototype 原型版发布!

    /* 源码作者: 石不易(Louis Shi) 联系方式: http://www.shibuyi.net =============================================== ...

  5. 2017.10.9 JVM入门学习

    1.什么是JVM JVM是Java Virtual Machine(Java虚拟机)的缩写,JVM是一种用于计算设备的规范,它是一个虚构出来的计算机,是通过在实际的计算机上仿真模拟各种计算机功能来实现 ...

  6. removing vmware debugger from visual studio

    removing vmware debugger from visual studio by Ross on 十月 14, 2010 at 5:30 下午 under Visual Studio |  ...

  7. mac 开机白屏,卡进度条,无法进入系统

    几个月前我的老Mac又一次的坏掉了,现在想起来就记录一下,哎,话说Apple的东西吧,好用是好用,一般都不会坏,质量保证,但是如果一旦坏了,那就是大问题!(坏了第一时间就应该打电话给apple客服小姐 ...

  8. javascript入门笔记5-事件

    1.继续循环continue; continue的作用是仅仅跳过本次循环,而整个循环体继续执行. 语句结构: for(初始条件;判断条件;循环后条件值更新) { if(特殊情况) { continue ...

  9. Python 文件访问模式

    f = open('xxx文件', '访问模式') r    以只读方式打开文件(read).文件的指针将会放在文件的开头.默认模式. w   打开一个文件只用于写入(write).如果该文件已存在则 ...

  10. 关于props的注意事项!

    起于昨晚大半夜在群里看到有人问这个问题,在子组件的data属性里重新赋值props属性 this.a = this.propA,不生效! 提示了他如果是异步的话,就要注意watch.决定今日敲个dem ...