import MySQLdb
con = MySQLdb.connect(host="localhost", user="root", passwd="123456",db="xblog",port=3306)
完成python的数据库连接, 但是不能在这个对象上直接对数据库进行操作, 还需要获取对应的操作游标才能进行数据库的操作
cur = con.cursor()
cur.execute('create table stu_info (name char(128) not null default "", age tinyint(3) not null default 0, sex enum("man","femal") not null default "man") engine=innodb ')
0L
cur.execute 返回执行的sql 影响的行数, 因为这里是创建数据库, 所以是0L行。但到这里还并没有真正执行了sql语句, 必须使用MySQLdb.commit才是真正执行完毕
con.commit()
cur.execute("insert into stu_info (name, age, sex) values ('Yi_Zhi_Yu',25,'man')")
con.commit()
或者用下面这种方式:
cur.execute("insert into stu_info (name, age, sex) values (%s,%s,%s)", ("Tony",25, "man"))
con.commit()
第二种方式可以传递多列表值,即可以批量的导入数据进数据库。
cur.executemany("insert into stu_info (name, age, sex) values (%s,%s,%s)",(("LiMei",26,"femal"),("YuanYuan",28,"femal")))
con.commit()
cur.execute("select * from stu_info")
stus = cur.fetchall()
for stu in stus:
print "name: %s; age: %d; sex: %s" %(stu[0], stu[1], stu[2])
name: Yi_Zhi_Yu; age: 25; sex: man
name: Tony; age: 25; sex: man
name: LiMei; age: 26; sex: femal
name: YuanYuan; age: 28; sex: femal
name: Yi_Zhi_Yu; age: 25; sex: man
cur = con.cursor(cursorclass=MySQLdb.cursors.DictCursor)
cur.execute("select * from stu_info")
cur.fetchall()
({'age': 25, 'name': 'Yi_Zhi_Yu', 'sex': 'man'},
{'age': 25, 'name': 'Tony', 'sex': 'man'},
{'age': 26, 'name': 'LiMei', 'sex': 'femal'},
{'age': 28, 'name': 'YuanYuan', 'sex': 'femal'},
{'age': 25, 'name': 'Yi_Zhi_Yu', 'sex': 'man'})
con.close()
Python 中对数据的操作, 增删改均要在指针对象执行了sql语句后, 使用连接对象commit, 查询的结果使用指针对象的fetch系列方法获取
diancody CSDN博客