标签:
# 打开数据库连接
db = MySQLdb.connect("localhost","root","123qwe","host_list" )
# 使用cursor()方法获取操作游标
cursor = db.cursor()
# 使用execute方法执行SQL语句
cursor.execute("SELECT VERSION()")
# 使用 fetchone() 方法获取一条数据库。【以-行计数】
data = cursor.fetchone()
print "Database version : %s " % data
# 关闭数据库连接
db.close()
2、插去数据;
# 创建数据表SQL语句
sql = """CREATE TABLE EMPLOYEE ( FIRST_NAME CHAR(20) NOT NULL, LAST_NAME CHAR(20), AGE INT, SEX CHAR(1), INCOME FLOAT )"""
try:
# 执行sql语句
cursor.execute(sql)
# 提交到数据库执行
db.commit()
except:
# Rollback in case there is any error
db.rollback()
#!/usr/bin/python
#coding:utf-8
try:
import MySQLdb
db = MySQLdb.connect("localhost","root","123qwe","host_list" )
cursor = db.cursor()
v_list = []
for i in range(10):
v_list.append(("linux%s" %i,"moban%s" %i,"12%s" %i,"M", "2000"))
print v_list
cursor.executemany( "INSERT INTO EMPLOYEE \
VALUES (%s, %s, %s, %s, %s)", v_list)
cursor.close()
db.commit()
db.close()
except MySQLdb.Error,e:
print ‘Mysql Error Msg:‘,e
标签:
原文地址:http://www.cnblogs.com/zhangju/p/5720211.html