python加数据库_python连接数据库并插入数据

#coding=utf-8

importMySQLdbtry:

conn=MySQLdb.connect(

host="127.0.0.1",

port=3306,

user="root",

passwd="123456",#db="juntest",另外写一种建表的方法

charset="utf8")

conn.select_db('juntestDBnew')#选择一个数据库

cur =conn.cursor()

cur.execute("drop table if exists emp_info2;")

cur.execute("drop table if exists salary2;")

cur.execute('''create table emp_info2(

id int not null auto_increment,

name varchar(30) not null,

sex char(4) default null,

dept varchar(10),

mobile varchar(11) not null unique,

birthday date default "0000-00-00",

primary key(id)

)engine=innodb character set utf8 comment 'employer info';''')

cur.execute('''create table salary2(

id int not null auto_increment,

emp_id int not null,

salary int not null,

primary key(id)

)engine=innodb character set utf8 comment 'employer salary info';''')

cur.close()

conn.close()print u"创建数据表成功!"

exceptMySQLdb.Error, e:print "Mysql Error %d: %s" % (e.args[0], e.args[1])

你可能感兴趣的:(python加数据库)