python针对mysql数据库学习而言,如何把table的信息传输到html文件中

博客分类:
近来在看python,于是,将某个shell实现过的功能用python实现下
1 python 操作mysql 需要有 MySQLdb 这个库的支持,一般需要单独安装
2 MySQLdb库只能执行sql语句,对于sql文件执行,比较麻烦,所以用了subprocess库的方法Popen
import MySQLdb
from subprocess import Popen,PIPE
sqlta = "/usr/local/webserver/scripts/ta.sql"
sqlclita = "/usr/local/webserver/scripts/clita.sql"
Platform = raw_input('Please Enter Platform:')
Server = raw_input('Please Enter Server:')
LogTa = "LogTa_"+Platform+"_"+Server
LogCliTa = "LogCliTa_"+Platform+"_"+Server
host = "192.168.0.1"
usr = "admin"
passwd = "admin8SQBL"
port = 3303
conn = MySQLdb.connect(host=host,user=usr,passwd=passwd,port=port)
cur = conn.cursor()
cur.execute('create database IF NOT EXISTS '+LogTa)
cur.execute('create database IF NOT EXISTS '+LogCliTa)
cur.close()
conn.close()
except MySQLdb.Error,e:
print "Mysql Error %d: %s" % (e.args[0], e.args[1])
process = Popen('/usr/local/webserver/mysql/bin/mysql -h%s -P%s -u%s -p%s %s'
%(host, port, usr, passwd, LogTa), stdout=PIPE, stdin=PIPE, shell=True)
output = process.communicate('source '+sqlta)
process = Popen('/usr/local/webserver/mysql/bin/mysql -h%s -P%s -u%s -p%s %s'
%(host, port, usr, passwd, LogCliTa), stdout=PIPE, stdin=PIPE, shell=True)
output = process.communicate('source '+sqlclita)
相当于用MySQLdb库创建了数据库,然后用Popen,进行sql文件的执行操作。Popen()函数相当于用shell来执行..
alfred_long
浏览: 443754 次
来自: 北京
看了很多篇博主的帖子,最近注册了之后才可以发表评论。不知道博主 ...
写的很好,解决了我的问题,thinks very much
太牛逼了,不过那个ctags的我没安装成功,步骤不是很详细
ygqwan 写道Failed opening control ...
从入门到精通,不错。 http://www.ihref.com ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'Python连接mysql数据库及python使用mysqldb连接数据库教程
& 发布时间: 10:31:19 & 作者:佚名 &
如何可以使Python连接mysql数据库或使用mysqldb连接数据库呢,下面就为大家系统的介绍总结一下,希望可以对大家有多帮助
做python的时候需要用到数据库,于是自己重新整理了一下数据库的知识,并且熟悉了python中MysqlDB模块的功能和函数等接口,现在系统地来总结一下吧:
首先你要做的还是下载相应的模块并且安装啦,下载地址自己搜,网上有很多,安装的话也很好办,安装之后python的安装目录下的Lib文件夹下的site-packages文件夹下的MySQLdb文件夹,这之中存放的便是该模块的定义。准备工作做好之后我们需要在源码中import MySQLdb
数据库的连接:
模块引入之后我们就需要和数据库进行连接了,实例代码如下:
db = MySQLdb.connect(&localhost&,&root&,&123456&,&myciti& )
这三个关键参数的含义一目了然:第一个为服务器的地址,第二个为用户名,第三个为dbms密码,第四个为要访问的数据库,其实该connect函数的参数不止这些,不过由于其有默认值而且大多数情况下不用修改,因而省略了。这里做如下列表:
host,连接的数据库服务器主机名,默认为本地主机(localhost)。
user,连接数据库的用户名,默认为当前用户。
passwd,连接密码,没有默认值。
db,连接的数据库名,没有默认值。
conv,将文字映射到Python类型的字典。默认为MySQLdb.converters.conversions
cursorclass,cursor()使用的种类,默认值为MySQLdb.cursors.Cursor。
compress,启用协议压缩功能。
named_pipe,在windows中,与一个命名管道相连接。
init_command,一旦连接建立,就为数据库服务器指定一条语句来运行。
read_default_file,使用指定的MySQL配置文件。
read_default_group,读取的默认组。
unix_socket,在unix中,连接使用的套接字,默认使用TCP。
port,指定数据库服务器的连接端口,默认是3306
大家可能会注意到源码中没有用到端口号,这是因为MySQLdb的connect函数的该参数的默认值便是3306,如果你在安装mysql的时候修改了数据库的端口号,那么你就需要在源码中加上该参数的修改值了。
一,安装mysql
如果是windows 用户,mysql 的安装非常简单,直接下载安装文件,双击安装文件一步一步进行操作即可。
Linux 下的安装可能会更加简单,除了下载安装包进行安装外,一般的linux 仓库中都会有mysql ,我们只需要通过一个命令就可以下载安装:
Ubuntu\deepin
&&sudo apt-get install mysql-server
&&Sudo apt-get install mysql-client
centOS/redhat
&&yum install mysql
二,安装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目录:
&&python setup.py install
测试非常简单,检查MySQLdb 模块是否可以正常导入。
fnngj@fnngj-H24X:~/pyse$ python
Python 2.7.4 (default, Sep 26 :56)
[GCC 4.7.3] on linux2
Type &help&, &copyright&, &credits& or &license& for more information.
&&& import MySQLdb
没有报错提示MySQLdb模块找不到,说明安装OK ,下面开始使用python 操作数据库之前,我们有必要来回顾一下mysql的基本操作:
四,mysql 的基本操作
$ mysql -u root -p (有密码时)
$ mysql -u root (无密码时)
mysql& // 查看当前所有的数据库
+--------------------+
| Database |
+--------------------+
| information_schema |
| csvt04 |
| performance_schema |
+--------------------+
6 rows in set (0.18 sec)
mysql& //作用与test数据库
Database changed
mysql& //查看test库下面的表
Empty set (0.00 sec)
//创建user表,name 和password 两个字段
mysql& CREATE TABLE user (name VARCHAR(20),password VARCHAR(20)); Query OK, 0 rows affected (0.27 sec)
//向user表内插入若干条数据
mysql& insert into user values('Tom','1321');Query OK, 1 row affected (0.05 sec)
mysql& insert into user values('Alen','7875');Query OK, 1 row affected (0.08 sec)
mysql& insert into user values('Jack','7455');Query OK, 1 row affected (0.04 sec)
//查看user表的数据
mysql& select *+------+----------+
| name | password |
+------+----------+
| Tom | 1321 |
| Alen | 7875 |
| Jack | 7455 |
+------+----------+
3 rows in set (0.01 sec)
//删除name 等于Jack的数据
mysql& delete from user where name = 'Jack';Query OK, 1 rows affected (0.06 sec)
//修改name等于Alen 的password 为 1111
mysql& update user set password='1111' where name = 'Alen';Query OK, 1 row affected (0.05 sec)
Rows matched: 1 Changed: 1 Warnings: 0
//查看表内容
mysql& select *+--------+----------+
| name | password |
+--------+----------+
| Tom | 1321 |
| Alen | 1111 |
+--------+----------+
3 rows in set (0.00 sec)
五,python 操作mysql数据库基础
#coding=utf-8import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
cur = conn.cursor()#创建数据表#cur.execute(&create table student(id int ,name varchar(20),class varchar(30),age varchar(10))&)#插入一条数据#cur.execute(&insert into student values('2','Tom','3 year 2 class','9')&)#修改查询条件的数据#cur.execute(&update student set class='3 year 1 class' where name = 'Tom'&)#删除查询条件的数据#cur.execute(&delete from student where age='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(&create table student(id int ,name varchar(20),class varchar(30),age varchar(10))&)
通过游标cur 操作execute()方法可以写入纯sql语句。通过execute()方法中写如sql语句来对数据进行操作。
&&&cur.close()
cur.close() 关闭游标
&&&conn.commit()
conn.commit()方法在提交事物,在向数据库插入一条数据时必须要有这个方法,否则数据不会被真正的插入。
&&&conn.close()
Conn.close()关闭数据库连接
六,插入数据
通过上面execute()方法中写入纯的sql语句来插入数据并不方便。如:
&&&cur.execute(&insert into student values('2','Tom','3 year 2 class','9')&)
我要想插入新的数据,必须要对这条语句中的值做修改。我们可以做如下修改:
#coding=utf-8import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
cur = conn.cursor()#插入一条数据sqli=&insert into student values(%s,%s,%s,%s)&cur.execute(sqli,('3','Huhu','2 year 1 class','7'))
cur.close()
conn.commit()
conn.close()
假如要一次向数据表中插入多条值呢?
#coding=utf-8import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
cur = conn.cursor()#一次插入多条记录sqli=&insert into student values(%s,%s,%s,%s)&cur.executemany(sqli,[
('3','Tom','1 year 1 class','6'),
('3','Jack','2 year 1 class','7'),
('3','Yaheng','2 year 2 class','7'),
cur.close()
conn.commit()
conn.close()
executemany()方法可以一次插入多条值,执行单挑sql语句,但是重复执行参数列表里的参数,返回值为受影响的行数。
七,查询数据
也许你已经尝试了在python中通过
&&&cur.execute(&select * from student&)
来查询数据表中的数据,但它并没有把表中的数据打印出来,有些失望。
来看看这条语句获得的是什么
&&&aa=cur.execute(&select * from student&)
&&&print aa
它获得的只是我们的表中有多少条数据。那怎样才能获得表中的数据呢?进入python shell
&&& import MySQLdb&&& conn = MySQLdb.connect(host='localhost',port = 3306,user='root', passwd='123456',db ='test',)&&& cur = conn.cursor()&&& cur.execute(&select * from student&)5L
&&& cur.fetchone()
(1L, 'Alen', '1 year 2 class', '6')&&& cur.fetchone()
(3L, 'Huhu', '2 year 1 class', '7')&&& cur.fetchone()
(3L, 'Tom', '1 year 1 class', '6')
...&&&cur.scroll(0,'absolute')
  fetchone()方法可以帮助我们获得表中的数据,可是每次执行cur.fetchone() 获得的数据都不一样,换句话说我没执行一次,游标会从表中的第一条数据移动到下一条数据的位置,所以,我再次执行的时候得到的是第二条数据。
  scroll(0,'absolute') 方法可以将游标定位到表中的第一条数据。
还是没解决我们想要的结果,如何获得表中的多条数据并打印出来呢?
#coding=utf-8import MySQLdb
conn= MySQLdb.connect(
host='localhost',
port = 3306,
user='root',
passwd='123456',
db ='test',
cur = conn.cursor()#获得表中有多少条数据aa=cur.execute(&select * from student&)print aa#打印表中的多少数据info = cur.fetchmany(aa)for ii in info: print ii
cur.close()
conn.commit()
conn.close()
  通过之前的print aa 我们知道当前的表中有5条数据,fetchmany()方法可以获得多条数据,但需要指定数据的条数,通过一个for循环就可以把多条数据打印出啦!执行结果如下:
5(1L, 'Alen', '1 year 2 class', '6')
(3L, 'Huhu', '2 year 1 class', '7')
(3L, 'Tom', '1 year 1 class', '6')
(3L, 'Jack', '2 year 1 class', '7')
(3L, 'Yaheng', '2 year 2 class', '7')
[Finished in 0.1s]
大家感兴趣的内容
12345678910
最近更新的内容博客分类:
项目心得:Python是们非常有意思的语言,之前在51cto看老男孩Python培训视频的时候看他们做的项目是采用文件存储数据和读取数据,而且界面排版我个人不是非常喜欢.我认为将数据存储在Mysql数据库中会更加完美。
项目内容:(1)Python 操作Mysql数据库的方法
&&&&&&&&& (2)Python 面向对象的编程
&&&&&&&&& (3)Python Import方法
&&&&&&&&& (4)Python 的While,Break,Continue,for if 语句结合使用
&&&&&&&&& (5)Python的列表,元组,字符串等等
大体掌握上述东西,此项目做起来就比较顺手.
同时有些方面可能没有考虑完美,也没有很多的注释,但是时间的问题,,以后会逐渐更改和完善
博客声明:本文为原创,如果转载请注明出处.iotos.iteye.com
1.Mysql部分:
staff表
id&&&&&&&&
bigint(12)&&&
0&&&&&& &&&&&&
name&&&&&&
varchar(20)&&
NULL&&& &&&&&&
sex&&&&&&&
enum('M','W')
NULL&&& &&&&&&
birthday&&
varchar(20)&&
NULL&&& &&&&&&
age&&&&&&&
int(4)&&&&&&&
NULL&&& &&&&&&
tel&&&&&&&
bigint(12)&&&
NULL&&& &&&&&&
department
varchar(6)&&&
NULL&&& &&&&&&
salary&&&&
float&&&&&&&&
NULL&&& &&&&&&
2.部分代码:
Company.py
#!/usr/bin/python
#-*- coding:utf-8 -*-
######################################################################
## Filename:
company.py
## Copyright (C) 2014.6
## Author:
TangMeiHao@
## Description:
python 实现企业人事管理系统
######################################################################
import mysql
import sys
import time
class company:
thisyear=int(time.strftime("%Y"))
birthday=''
department=''
def __Menu__(self):
menus="""\033[35;38m
[........SELECT YOUR FUNCTION........]
2:FIND HrTable
3:MODI HrTable
4:SHOW HrRable
6:EXIT SYSTEM
\033[0m"""
print menus
company.opt=raw_input("\t\t\t\033[32;38m
.........\033[0m\n")
def __Select__(self):
while True:
company.__Menu__(self)
if company.opt=='1':
while True:
company.__Add__(self)
opt2=raw_input("\t\t\t\033[31;38m
CONTINUE ADD(y/Y)
........\033[0m\n")
if opt2=='Y' or opt2=='y'or opt2=='':
elif company.opt=='2':
while True:
company.__FIND__(self)
elif company.opt=='3':
while True:
company.__Modify__(self)
opt2=raw_input("\t\t\t\033[31;38m
CONTINUE MOD(y/Y)
........\033[0m\n")
if opt2=='y' or opt2=='Y' or opt2=='':
elif company.opt=='4':
while True:
company.__Show__(self)
elif company.opt=='5':
while True:
company.__Delete__(self)
elif company.opt=='6':
while True:
company.__Exit__(self)
print "\t\t\t\033[31;38m
[.........
选项错误(AGAIN):
......]\033[0m\n"
def __Add__(self):
while True:
Id=raw_input("\t\t\t\033[31;38m
[.........
INPUT ID FOR ADD:
......]\033[0m\n")
lenid=len(Id)
intId=int(Id) #将其单独转换为整形,与下面的i[0]数据库读出来的ID进行比较
Addinstance=mysql.cur
Addconn=mysql.conn
MysqlId=Addinstance.execute('select id from staff')
MysqlIds=Addinstance.fetchmany(1000)
flag=False #flag为False,表示这个编号不存在,为True存在,进行再一次输入
for i in MysqlIds:
if i[0]==intId: #判断是否已经存在这个Id,Id为主键
if flag==True:
print "\t\t\t\033[31;38m
[.........
......]\033[0m\n" % Id
if lenid==11: #判断输入的Id长度是否为11
company.name=raw_input("\t\t\t\033[31;38m
INPUT NAME:
.........\033[0m\n")
company.sex=raw_input("\t\t\t\033[31;38m
INPUT SEX:
.........\033[0m\n")
company.birthday=raw_input("\t\t\t\033[31;38m
INPUT BIRTHDAY:
.........\033[0m\n")
company.age=int(raw_input("\t\t\t\033[31;38m
INPUT AGE:
.........\033[0m\n"))
company.tel=int(raw_input("\t\t\t\033[31;38m
INPUT TEL:
.........\033[0m\n"))
company.department=raw_input("\t\t\t\033[31;38m
INPUT DEPARTMENT:.........\033[0m\n")
company.salary=int(raw_input("\t\t\t\033[31;38m
INPUT SALARY:
.........\033[0m\n"))
value=[company.id,company.name,company.sex,company.birthday,company.age,company.tel,company.department,company.salary]
Addinstance=mysql.cur
Addconn=mysql.conn
Addinstance.execute('insert into staff values(%s,%s,%s,%s,%s,%s,%s,%s)',value)
Addconn.commit()
def __FIND__(self):
while True:
Id=int(raw_input("\t\t\t\033[31;38m
[.........
INPUT ID FOR FIND: ......]\033[0m\n"))
Addinstance=mysql.cur
Addconn=mysql.conn
MysqlId=Addinstance.execute('select id from staff')
MysqlIds=Addinstance.fetchmany(1000)
flag=False #flag为False,表示这个编号不存在,为True存在,进行再一次输入
for i in MysqlIds:
if i[0]==Id: #判断是否已经存在这个Id,Id为主键
if flag==False:
print "\t\t\t\033[31;38m
[.........
......]\033[0m\n" % Id
a=mysql.cur
a.execute('select * from staff where id=%s',Id)
results=a.fetchmany(1000)
for r in results:
birthday=r[3]
salary=r[7]
value=(Id,name,sex,birthday,age,tel,dep,salary)
result="""
""" % value
print "\t\t\t\033[31;38m
[.........
%s信息如下:.....]\033[0m\n" % Id
print result
def __Show__(self):
a=mysql.cur
a.execute('select * from staff ')
results=a.fetchmany(1000)
for r in results:
birthday=r[3]
salary=r[7]
value=(Id,name,sex,birthday,age,tel,dep,salary)
result="""
""" % value
print "\t\t\t\033[31;38m
[.........
%s信息如下:.....]\033[0m\n" % Id
print result
def __Modify__(self):
while True:
Modinstance=mysql.cur
Modconn=mysql.conn
Id=int(raw_input("\t\t\t\033[31;38m
[.........
INPUT ID FOR MOD:
......]\033[0m\n"))
MysqlId=Modinstance.execute('select id from staff')
MysqlIds=Modinstance.fetchmany(1000)
flag=False
for i in MysqlIds:
if i[0]==Id:
if flag==False:
print "\t\t\t\033[31;38m
[.........
......]\033[0m\n" % Id
Modinstance.execute('select * from staff where id=%s',Id)
results=Modinstance.fetchmany(1000)
for r in results:
birthday=r[3]
salary=r[7]
value=(Id,name,sex,birthday,age,tel,dep,salary)
result="""
""" % value
print "\t\t\t\033[31;38m
[.........
%s信息如下:
......]\033[0m\n" % name
print result
print "\t\t\t\033[31;38m
[.........
%s修改信息:
......]\033[0m\n" % name
modid=raw_input("\t\t\t\033[31;38m
输入编号:\033[0m")
modname=raw_input("\t\t\t\033[31;38m
输入姓名:\033[0m")
modsex=raw_input("\t\t\t\033[31;38m
输入性别:\033[0m")
modbirthday=raw_input("\t\t\t\033[31;38m
输入出生:\033[0m")
modage=raw_input("\t\t\t\033[31;38m
输入年龄:\033[0m")
modtel=raw_input("\t\t\t\033[31;38m
输入电话:\033[0m")
moddep=raw_input("\t\t\t\033[31;38m
输入部门:\033[0m")
modsalary=raw_input("\t\t\t\033[31;38m
输入薪水:\033[0m")
modify_value=(modid,modname,modsex,modbirthday,modage,modtel,moddep,modsalary,Id)
Modinstance.execute("update staff set id=%s,name=%s,sex=%s,birthday=%s,age=%s,tel=%s, department=%s,salary=%s
where id=%s",modify_value)
Modconn.commit()
print "\t\t\t\033[31;38m
[.........
%s修改成功:
......]\033[0m\n" % name
def __Delete__(self):
Id=int(raw_input("\t\t\t\033[31;38m
[.........
INPUT ID FOR DEL:
......]\033[0m\n"))
Delinstance=mysql.cur
Delconn=mysql.conn
Delinstance.execute('select * from staff where id=%s',Id)
results=Delinstance.fetchmany(1000)
for r in results:
birthday=r[3]
salary=r[7]
value=(Id,name,sex,birthday,age,tel,dep,salary)
result="""
""" % value
print "\t\t\t\033[31;38m
[.........
%s信息如下:
......]\033[0m\n" % name
print result
while True:
char=raw_input("\t\t\t\033[31;38m
[.........
删除%s(Y/y)?:......]\033[0m\n" % name)
if char=='y' or char=='Y' or char=='':
Delinstance.execute('delete from staff where id=%s',Id)
print "\t\t\t\033[31;38m
[.........
%s删除成功:
......]\033[0m\n" % Id
def __Exit__(self):
sys.exit()
if __name__=='__main__':
COMinstance=company()
COMinstance.__Select__()
except KeyboardInterrupt:
项目截图:(随便截了两个图,太麻烦了)
1.
浏览: 20058 次
来自: 湖南永州
liujiaoshui 写道我看到了重点:webchat。。。 ...
我看到了重点:webchat。。。。是有这么个开源
alajl 写道没有多大的实际意义就是学习的时候练练手,当然P ...
没有多大的实际意义
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'个回答将html数据转换为字符串来解决问题。tostring = str(data)description = page_soup.findAll(&div&, {&class&: &ui-box-body&})
^这里findAll会返回一个匹配标签的列表,但是你需要传递一个字符串cursor.execute()。因此,你应该从这些匹配的标签中获取一个字符串。以下可能是一种方法来做到这一点:description = page_soup.findAll(&div&, {&class&: &ui-box-body&})
data_insert = description[0].get_text()
cursor.execute(add_data, data_insert)
扫描二维码扫描关注云+社区博客分类:
mysql官方提供了很多种connector,其中包括python的connector。
下载地址在:
直接安装即可。
在python中:
import mysql.connector
cnx = mysql.connector.connect(user='scott', password='tiger',
host='127.0.0.1',
database='employees')
cnx.close()
import datetime
import mysql.connector
cnx = mysql.connector.connect(user='scott', database='employees')
cursor = cnx.cursor()
query = ("SELECT first_name, last_name, hire_date FROM employees "
"WHERE hire_date BETWEEN %s AND %s")
hire_start = datetime.date()
hire_end = datetime.date()
cursor.execute(query, (hire_start, hire_end))
for (first_name, last_name, hire_date) in cursor:
print("{}, {} was hired on {:%d %b %Y}".format(
last_name, first_name, hire_date))
cursor.close()
cnx.close()
3. 输出到文件(使用当前日期做文件名)
import time
filename = 'page_list_'+str(time.strftime("%Y%m%d"))+'.txt'
output = open(filename,'w')
output.write(str(page_title).lstrip('(b\'').rstrip('\',)')+"\n")
output.close()
这里page_title是上面从数据库中检索出来的字段名。因为输出都是(b'pagename')的格式,所以又做了一些处理,删除了多余的字符。
这样,检索出的内容就可以直接保存到以日期为名字的文件中了。
浏览 11543
浏览: 61977 次
来自: 北京
***如果要对目录遍历,对所有文件都进行检查,可以用另一个py ...
(window.slotbydup=window.slotbydup || []).push({
id: '4773203',
container: s,
size: '200,200',
display: 'inlay-fix'}

我要回帖

更多关于 mysql数据库怎么用 的文章

更多推荐

版权声明:文章内容来源于网络,版权归原作者所有,如有侵权请点击这里与我们联系,我们将及时删除。

点击添加站长微信