MySQLdb的增删改查

#coding=utf-8
import MySQLdb

#建立数据库连接
connect = MySQLdb.connect(host=host, user=dbuser, passwd=dbpass, db=dbname, charset=charset)
#cursor = connect .cursor() #这种方式查询出来的结果是tuple
cursor = connect.cursor(cursorclass=MySQLdb . cursors . DictCursor) #这种方式的查询结果是dict

#INSERT --单条数据
sql = “INSERT INTO user (name, age, gneder) VALUES (%s, %s, %s)”
param = ('bright', '27', '1')
cursor.execute(sql, param)
cursor.close
connect.commit() #注意:如果不调用此方法插入语句不会真正执行,ADD/DELETE/UPDATE操作必须执行此函数。
#INSERT --多条数据
sql = “INSERT INTO user (name, age, gneder) VALUES (%s, %s, %s)”
param = (('bright', '27', '1'), ('jean', '27', '1'))
cursor.executemany(sql, param)
cursor.close
connect.commit() 

#DELETE
sql = "DELETE FROM user WHERE id=1"
cursor.execute(sql)
cursor.close()
connect.commit()

#UPDATE
sql = "UPDATE user SET name=%s,age=%s WHERE id=1"
param = ('jack', 28)
cursor.execute(sql, param)
cursor.close()
connect.commit()

#SELETE
result = []
sql = "SELECT * FROM user WHERE id>1 LIMIT 30"
cursor.execute(sql)
for row in self.__cursor.fetchall():
    result.append(row)
cursor.close()
connect.close() #关闭数据库连接

print result


 
 

你可能感兴趣的:(Python编程)