Python MySQLdb模块连接操作mysql数据库实例

yipeiwu_com5年前Python基础

mysql是一个优秀的开源数据库,它现在的应用非常的广泛,因此很有必要简单的介绍一下用python操作mysql数据库的方法。python操作数据库需要安装一个第三方的模块,在http://mysql-python.sourceforge.net/有下载和文档。

由于python的数据库模块有专门的数据库模块的规范,所以,其实不管使用哪种数据库的方法都大同小异的,这里就给出一段示范的代码:

#-*- encoding: gb2312 -*-
import os, sys, string
import MySQLdb

# 连接数据库 
try:
  conn = MySQLdb.connect(host='localhost',user='root',passwd='xxxx',db='test1')
except Exception, e:
  print e
  sys.exit()

# 获取cursor对象来进行操作

cursor = conn.cursor()
# 创建表
sql = "create table if not exists test1(name varchar(128) primary key, age int(4))"
cursor.execute(sql)
# 插入数据
sql = "insert into test1(name, age) values ('%s', %d)" % ("zhaowei", 23)
try:
  cursor.execute(sql)
except Exception, e:
  print e

sql = "insert into test1(name, age) values ('%s', %d)" % ("张三", 21)
try:
  cursor.execute(sql)
except Exception, e:
  print e
# 插入多条

sql = "insert into test1(name, age) values (%s, %s)" 
val = (("李四", 24), ("王五", 25), ("洪六", 26))
try:
  cursor.executemany(sql, val)
except Exception, e:
  print e

#查询出数据
sql = "select * from test1"
cursor.execute(sql)
alldata = cursor.fetchall()
# 如果有数据返回,就循环输出, alldata是有个二维的列表
if alldata:
  for rec in alldata:
    print rec[0], rec[1]


cursor.close()

conn.close()

相关文章

如何基于Python实现电子邮件的发送

如何基于Python实现电子邮件的发送

这篇文章主要介绍了如何基于Python实现电子邮件的发送,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下 利用Python smtpli...

Python使用add_subplot与subplot画子图操作示例

Python使用add_subplot与subplot画子图操作示例

本文实例讲述了Python使用add_subplot与subplot画子图操作。分享给大家供大家参考,具体如下: 子图:就是在一张figure里面生成多张子图。 Matplotlib对象...

Python兔子毒药问题实例分析

本文实例分析了Python兔子毒药问题。分享给大家供大家参考。具体分析如下: 问题大致是这样的:1000瓶无色无味的液体,其中一瓶为毒药,其它皆为清水,毒药只取一滴与清水混合为一瓶也可以...

PyQt5图形界面播放音乐的实例

安装Pygame pip install pygame import time import pygame pygame.init() print("播放音乐1") track =...

python 3.0 模拟用户登录功能并实现三次错误锁定

Python是一种解释型、面向对象、动态数据类型的高级程序设计语言。 Python由Guido van Rossum于1989年底发明,第一个公开发行版发行于1991年。 像Perl...