Linux下python连接MySQL数据库

来源:互联网 发布:美玩吧软件叫什么 编辑:程序博客网 时间:2024/06/05 01:47


Linux下python连接MySQL数据库方法

要连接数据库名称是hhh,用户名是tom,连接的数据表是 data_import,其中 data_import数据结构如下(5个属性):

mysql> desc data_import;+---------+-------------+------+-----+---------+-------+| Field   | Type        | Null | Key | Default | Extra |+---------+-------------+------+-----+---------+-------+| id      | char(10)    | YES  |     | NULL    |       || name    | char(10)    | YES  |     | NULL    |       || age     | char(10)    | YES  |     | NULL    |       || address | varchar(15) | YES  |     | NULL    |       || hobby   | varchar(15) | YES  |     | NULL    |       |+---------+-------------+------+-----+---------+-------+5 rows in set (0.01 sec)


Linux下python连接MySQL数据库完整例程:

#!/usr/bin/pythonimport MySQLdb #导入库conn = MySQLdb.connect(host="127.0.0.1",user="tom",passwd="123",db="hhh")#conn = MySQLdb.connect('localhost',"tom","123","hhh")#连接函数cur = conn.cursor()#获得指向当前数据库的指针#cur.execute('show tables;')cur.execute("select * from data_import;")#用execute()方法执行SQL语句result = cur.fetchall()#用fetchall()方法得到行信息for record in result:        print   "%s \t%s \t%s \t%s \t%s " % record#格式化输出cur.close()#关闭指针对象conn.close()#关闭数据库连接对象


运行结果(部分):

[root@localhost python]# ./python_mysql.py1       TOM     24      Beijing         football2       LIU     27      heibei  football3       JIM     26      shandong        football4       HAN     28      beijing         football5       MENG    25      beijing         tennis1       TOM     24      Beijing         football





原创粉丝点击