python操作mysql數據庫,查詢出來數據庫的值,並保存到文件中:
#-*-coding:utf-8-*-
import sys
import MySQLdb #引入mysql模塊
reload(sys)
sys.setdefaultencoding('utf-8') #這兩段話是改變python的編碼
conn = MySQLdb.connect(user='root',passwd='root',host='127.0.0.1',charset='utf8') #連接數據庫
conn.select_db('huang') #選擇數據庫
cur = conn.cursor() #查詢出來的數據保存在一個cursor中
cur.execute("insert into user(username,passwd) values('kk','kk')") #插入一條數據
s = cur.execute('select * from user') #查詢
file = open('1.txt','r+') #打開一個文件
desc = cur.description #cursor的頭部
username = str(desc[0][0])
passwd = str(desc[1][0])
id = str(desc[2][0])
length = len(username)
file.write(username+' '*(15-length))
length = len(passwd)
file.write(passwd+' '*(15-length))
length = len(id)
file.write(id+' '*(15-length)+'\n') #表頭部分
for n in cur.fetchmany(s): #取出來查詢出來的值
for x in n:
x = str(x)
print x
length = len(x)
file.write(str(x)+' '*(15-length))
file.write('\n')
file.close() #關閉
conn.commit()
cur.close()
conn.close()
數據庫中的表:/*
Navicat MySQL Data Transfer
Source Server : localhost
Source Server Version : 50067
Source Host : localhost:3306
Source Database : huang
Target Server Type : MYSQL
Target Server Version : 50067
File Encoding : 65001
Date: 2014-04-13 11:34:22
*/
SET FOREIGN_KEY_CHECKS=0;
-- ----------------------------
-- Table structure for `user`
-- ----------------------------
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
`username` varchar(50) default NULL,
`passwd` varchar(50) default NULL,
`id` int(15) NOT NULL auto_increment,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=71 DEFAULT CHARSET=utf8;
-- ----------------------------
-- Records of user
-- ----------------------------
INSERT INTO `user` VALUES ('admin', 'admin', '1');
INSERT INTO `user` VALUES ('huangteng', 'huangteng', '2');
INSERT INTO `user` VALUES ('kk', 'kk', '44');
INSERT INTO `user` VALUES ('荒唐', 'kk', '45');
INSERT INTO `user` VALUES ('kk', 'kk', '46');
查詢出來寫到文件中的結果:
username passwd id
admin admin 1
huangteng huangteng 2
kk kk 44
荒唐 kk 45
kk kk 46
第一次做練習,感覺python寫程序真的好厲害啊,比Java簡單,但是實現的功能也不比Java少