将mysql导入python_python mysql导入数据

[root@pku-fan MySQL]# cat limbs.sql

CREATE DATABASE cookbook;

USE cookbook;

DROP TABLE IF EXISTS limbs;

CREATE TABLE limbs

(

thing   VARCHAR(20),    # what the thing is

legs    INT,            # number of legs it has

arms    INT             # number of arms it has

);

INSERT INTO limbs (thing,legs,arms) VALUES('human',2,2);

INSERT INTO limbs (thing,legs,arms) VALUES('insect',6,0);

INSERT INTO limbs (thing,legs,arms) VALUES('squid',0,10);

INSERT INTO limbs (thing,legs,arms) VALUES('octopus',0,8);

INSERT INTO limbs (thing,legs,arms) VALUES('fish',0,0);

INSERT INTO limbs (thing,legs,arms) VALUES('centipede',100,0);

INSERT INTO limbs (thing,legs,arms) VALUES('table',4,0);

INSERT INTO limbs (thing,legs,arms) VALUES('armchair',4,2);

INSERT INTO limbs (thing,legs,arms) VALUES('phonograph',0,1);

INSERT INTO limbs (thing,legs,arms) VALUES('tripod',3,0);

INSERT INTO limbs (thing,legs,arms) VALUES('Peg Leg Pete',1,2);

INSERT INTO limbs (thing,legs,arms) VALUES('space alien',NULL,NULL);

[root@pku-fan MySQL]#mysql -u root -p < limbs.sql

编辑python程序

import MySQLdb

db_user = '不能说'

db_pw   = '秘密'

db = MySQLdb.connect('localhost', db_user, db_pw, 'cookbook')

c = db.cursor()

c.execute("select * from limbs")

print "%17s\t%7s\t%7s" % ('thing','legs','arms')

for thing,legs,arms in c.fetchall():

print "%17s\t%7s\t%7s" %(thing,legs,arms)

你可能感兴趣的:(将mysql导入python)