# 打开数据库连接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 errordb.rollback()
#!/usr/bin/python#coding:utf-8try:import MySQLdbdb = 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_listcursor.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