python使用mysql数据库示例代码
一,安装mysql
如果是windows用户,mysql的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可。
Linux下的安装可能会更加简单,除了下载安装包进行安装外,一般的linux仓库中都会有mysql,我们只需要通过一个命令就可以下载安装:
Ubuntu\deepin
>>sudoapt-getinstallmysql-server >>Sudoapt-getinstallmysql-client
centOS/redhat
>>yuminstallmysql
二,安装MySQL-python
要想使python可以操作mysql就需要MySQL-python驱动,它是python操作mysql必不可少的模块。
下载地址:https://pypi.python.org/pypi/MySQL-python/
下载MySQL-python-1.2.5.zip文件之后直接解压。进入MySQL-python-1.2.5目录:
>>pythonsetup.pyinstall
三,测试
测试非常简单,检查MySQLdb模块是否可以正常导入。
fnngj@fnngj-H24X:~/pyse$python Python2.7.4(default,Sep262013,03:20:56) [GCC4.7.3]onlinux2 Type"help","copyright","credits"or"license"formoreinformation. >>>importMySQLdb
没有报错提示MySQLdb模块找不到,说明安装OK,下面开始使用python操作数据库之前,我们有必要来回顾一下mysql的基本操作:
四,mysql的基本操作
$mysql-uroot-p(有密码时) $mysql-uroot(无密码时)
mysql>showdatabases;//查看当前所有的数据库 +--------------------+ |Database| +--------------------+ |information_schema| |csvt| |csvt04| |mysql| |performance_schema| |test| +--------------------+ 6rowsinset(0.18sec) mysql>usetest;//作用与test数据库 Databasechanged mysql>showtables;//查看test库下面的表 Emptyset(0.00sec) //创建user表,name和password两个字段 mysql>CREATETABLEuser(nameVARCHAR(20),passwordVARCHAR(20));QueryOK,0rowsaffected(0.27sec) //向user表内插入若干条数据 mysql>insertintouservalues('Tom','1321'); QueryOK,1rowaffected(0.05sec) mysql>insertintouservalues('Alen','7875'); QueryOK,1rowaffected(0.08sec) mysql>insertintouservalues('Jack','7455'); QueryOK,1rowaffected(0.04sec) //查看user表的数据 mysql>select*fromuser; +------+----------+ |name|password| +------+----------+ |Tom|1321| |Alen|7875| |Jack|7455| +------+----------+ 3rowsinset(0.01sec) //删除name等于Jack的数据 mysql>deletefromuserwherename='Jack'; QueryOK,1rowsaffected(0.06sec) //修改name等于Alen的password为1111 mysql>updateusersetpassword='1111'wherename='Alen'; QueryOK,1rowaffected(0.05sec) Rowsmatched:1Changed:1Warnings:0 //查看表内容 mysql>select*fromuser; +--------+----------+ |name|password| +--------+----------+ |Tom|1321| |Alen|1111| +--------+----------+ 3rowsinset(0.00sec)
五,python操作mysql数据库基础
#coding=utf-8 importMySQLdb conn=MySQLdb.connect( host='localhost', port=3306, user='root', passwd='123456', db='test', ) cur=conn.cursor() #创建数据表 #cur.execute("createtablestudent(idint,namevarchar(20),classvarchar(30),agevarchar(10))") #插入一条数据 #cur.execute("insertintostudentvalues('2','Tom','3year2class','9')") #修改查询条件的数据 #cur.execute("updatestudentsetclass='3year1class'wherename='Tom'") #删除查询条件的数据 #cur.execute("deletefromstudentwhereage='9'") cur.close() conn.commit() conn.close() >>>conn=MySQLdb.connect(host='localhost',port=3306,user='root',passwd='123456',db='test',)
Connect()方法用于创建数据库的连接,里面可以指定参数:用户名,密码,主机等信息。
这只是连接到了数据库,要想操作数据库需要创建游标。
>>>cur=conn.cursor()
通过获取到的数据库连接conn下的cursor()方法来创建游标。
>>>cur.execute("createtablestudent(idint,namevarchar(20),classvarchar(30),agevarchar(10))")
通过游标cur操作execute()方法可以写入纯sql语句。通过execute()方法中写如sql语句来对数据进行操作。
>>>cur.close()
cur.close()关闭游标
>>>conn.commit()
conn.commit()方法在提交事物,在向数据库插入一条数据时必须要有这个方法,否则数据不会被真正的插入。
>>>conn.close()
Conn.close()关闭数据库连接
六,插入数据
通过上面execute()方法中写入纯的sql语句来插入数据并不方便。如:
>>>cur.execute("insertintostudentvalues('2','Tom','3year2class','9')")
我要想插入新的数据,必须要对这条语句中的值做修改。我们可以做如下修改:
#coding=utf-8 importMySQLdb conn=MySQLdb.connect( host='localhost', port=3306, user='root', passwd='123456', db='test', ) cur=conn.cursor() #插入一条数据 sqli="insertintostudentvalues(%s,%s,%s,%s)" cur.execute(sqli,('3','Huhu','2year1class','7')) cur.close() conn.commit() conn.close()
假如要一次向数据表中插入多条值呢?
#coding=utf-8 importMySQLdb conn=MySQLdb.connect( host='localhost', port=3306, user='root', passwd='123456', db='test', ) cur=conn.cursor() #一次插入多条记录 sqli="insertintostudentvalues(%s,%s,%s,%s)" cur.executemany(sqli,[ ('3','Tom','1year1class','6'), ('3','Jack','2year1class','7'), ('3','Yaheng','2year2class','7'), ]) cur.close() conn.commit() conn.close()
executemany()方法可以一次插入多条值,执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数。
七,查询数据
也许你已经尝试了在python中通过
>>>cur.execute("select*fromstudent")
来查询数据表中的数据,但它并没有把表中的数据打印出来,有些失望。
来看看这条语句获得的是什么
>>>aa=cur.execute("select*fromstudent") >>>printaa 5
它获得的只是我们的表中有多少条数据。那怎样才能获得表中的数据呢?进入pythonshell
>>>importMySQLdb >>>conn=MySQLdb.connect(host='localhost',port=3306,user='root',passwd='123456',db='test',) >>>cur=conn.cursor() >>>cur.execute("select*fromstudent") 5L >>>cur.fetchone() (1L,'Alen','1year2class','6') >>>cur.fetchone() (3L,'Huhu','2year1class','7') >>>cur.fetchone() (3L,'Tom','1year1class','6') ... >>>cur.scroll(0,'absolute')
fetchone()方法可以帮助我们获得表中的数据,可是每次执行cur.fetchone()获得的数据都不一样,换句话说我没执行一次,游标会从表中的第一条数据移动到下一条数据的位置,所以,我再次执行的时候得到的是第二条数据。
scroll(0,'absolute')方法可以将游标定位到表中的第一条数据。
还是没解决我们想要的结果,如何获得表中的多条数据并打印出来呢?
#coding=utf-8 importMySQLdb conn=MySQLdb.connect( host='localhost', port=3306, user='root', passwd='123456', db='test', ) cur=conn.cursor() #获得表中有多少条数据 aa=cur.execute("select*fromstudent") printaa #打印表中的多少数据 info=cur.fetchmany(aa) foriiininfo: printii cur.close() conn.commit() conn.close()
通过之前的printaa我们知道当前的表中有5条数据,fetchmany()方法可以获得多条数据,但需要指定数据的条数,通过一个for循环就可以把多条数据打印出啦!执行结果如下:
5 (1L,'Alen','1year2class','6') (3L,'Huhu','2year1class','7') (3L,'Tom','1year1class','6') (3L,'Jack','2year1class','7') (3L,'Yaheng','2year2class','7') [Finishedin0.1s]
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持毛票票。