MySQLdb模块默认是不安装的,需要我们手动安装
1、记得要安装 python-devel mysql-devel(mariadb-devel),否则可能会遇到 mysql_config 丢失的问题
2、我是用 pip 包管理器去安装,没有安装 pip 的请自行百度 easy_install 和 pip 的安装方法
安装
pip install MySQL-python
实例
import MySQLdb #连接数据库 conn = MySQLdb.connect(host="localhost", user="username", passwd="password", db="dbname", prot=3306) #获取游标 cursor = conn.cursor() #切换数据库 无需重新获取cursor conn切换时其下的cursor也会被自动切换 conn.select_db("users") #执行sql语句 返回结果集记录数 cursor.execute("select * from `users`") #取当前cursor指针后的一条数据 cursor指针下移1位 cursor.fetchone() #取当前cursor指针后的多条数据 cursor指针下移5位 cursor.fetchmany(5) #取当前cursor指针后的所有数据 cursor指针下移到最尾 rows = cursor.fetchall() #查询结果 for row in rows: print row #绝对回滚 cursor 回滚到结果集的第几条 cursor.scroll(0, mode="absolute") #当前 cursor 指针下移 2 位 cursor.scroll(2, mode="relative") #当前 cursor 指针上移 2 位 cursor.scroll(-2, mode="relative") #预处理一下 返回插入记录数 cursor.execute("insert into `users`(`name`, `age`, `sex`) values(%s, %s, %s)", ["sallency", 26, "male"]); #执行多条语句 rows = [("james", 30, "male"), ("lucy", 23, "female"), ("lilei", 23, "male")] #插入多条数据 元素为tunpl的list 返回插入记录数 cursor.executemany("insert into `users`(`name`, `age`, `sex`) values(%s, %s, %s)", rows); #注意 如果是 InnoDb引擎需使用事务处理机制 cursor.commit() cursor.rollback() #调用过程 cursor.callproc('procName') #关闭cursor cursor.close() #关闭连接 conn.close()
异常处理
try: your code .... except MySQLdb.Error,e: print "Mysql Error %d: %s" % (e.args[0], e.args[1])
conn 为数据库连接
conn.select_db()
conn.close()
cursor 为 conn 的操作
execute()
executemany(sql, [(),(),()])
fetchone()
fetchmany()
fetchall()
scroll()
callproc()
commit()
close()