Python操作mysql

来源:互联网 发布:ug加工编程 编辑:程序博客网 时间:2024/06/05 04:48
一、MySQLdb包的安装1. 在win环境下,下载MySQL-Python-1.2.3,有两种方式:(1) 下载src源码.tar.gz(这个源码需要build编译再安装.egg包(当于.jar包));不过这种方法之后需要修改环境变量和MySQLdb.conf文件夹里的配置文件等等,具体网上去搜对应版本,我用的第二种方法,在python命令行里直接import MySQLdb;没有出现任何问题。(2) 直接下载MySQL-python-1.2.3.exe安装包(双击直接安装);这里直接安装的.exe,在python命令行里import没问题,在PyCharm里import没问题,但在pydev里引入就提示”uncheck package”,估计是pydev这个插件本身就有一些不完善的功能,要不就是最容易忽略的错误:忘记设置环境变量或者环境变量设置的路径错误。2. 解决eclipse里pydev插件不能引入MySQLdb包的问题:强制编译,而不仅是要在构建路径里引入库文件、.egg包(当于.jar包)等解决方案:Eclipse中,windows==>preference==>Pydev中,配置Interpreter-Python的ForcedBuiltins选项卡内容,手动添加内容MySQLdb,将模块强制编译进去。如果仅操作"构建路径System PYTHONPATH"的内容,引入库文件,无论如何不会解决问题。一定要强制编译进去!!! 二、连接数据库python连接mysql主要用到了游标cursor来访问,这个是MySQLdb自带的。补充几个对象的方法和属性:1.connection的参数:conn=MySQLdb.connect(“localhost”, “root”, “123456”, “testdb”)                 亦作conn = MySQLdb.connect(host=’localhost’,user=’root’, passwd=’123456’, db=’testdb’)注意这里没有写明端口号port=3306,是因为MySQLdb默认端口号为3306,不用指定,如果你自己改了,就要写上。connection的参数:host,连接的数据库服务器主机名,默认为本地主机(localhost)。user,连接数据库的用户名,默认为当前用户。passwd,连接密码,没有默认值。db,连接的数据库名,没有默认值。port,指定数据库服务器的连接端口,默认是3306conv,将文字映射到Python类型的字典。默认为MySQLdb.converters.conversionscursorclass,cursor()使用的种类,默认值为MySQLdb.cursors.Cursor。compress,启用协议压缩功能。named_pipe,在windows中,与一个命名管道相连接。init_command,一旦连接建立,就为数据库服务器指定一条语句来运行。read_default_file,使用指定的MySQL配置文件。read_default_group,读取的默认组。unix_socket,在unix中,连接使用的套接字,默认使用TCP。 2.connection(连接)对象 方法名                     作用conn. close()                  关闭数据库conn.commit()                提交当前事务----- 必须sql写完后要提交commit(),尤其是insert, update, delete时,否则数据库没有变化!!! ----- 而像select这种普通的查询,不涉及修改数据库的,是否commit()没有关系conn.rollback()              取消当前事务   ---- 异常处理except Exception:里最好还是加上回滚rollback()conn.cursor()           获取当前连接的游标对象conn.rrorhandler(cxn,cur,errcls,errval)  作为已给游标的句柄 3.cursor游标对象属性及方法(1) cursor执行命令的方法callproc(sql, procname, args)    执行存储过程,接收参数为存储过程名和参数列表,返回值为受影响的行数execute(sql,param, args)     执行单条sql语句,接收参数param,返回值为args受影响的行数executemany(sql,param, args)  执行多条sql语句,接收参数param,返回值为args受影响的行数next()            使用迭代对象得到结果的下一行nextset() / nestset(self):    移动到下一个结果集(如果支持的话)close()           关闭游标connection       创建此游标的连接(可选)(2) cursor用来接收返回值的方法fetchone()        返回一条结果行fetchall(self)        匹配所有剩余结果fetchmany(size-cursor,arraysize)  匹配结果的下几行rowcount         读取数据库表中的行数,最后一次execute()返回或影响的行数scroll(self, value, mode=’relative’):移动指针到某一行。如果mode=’relative’,则表示从当前所在行移动value条,如果mode=’absolute’,则表示从结果集的第一行移动value条arraysize        使用fetchmany()方法时一次取出的记录数,默认为1discription      返回游标的活动状态,包括(7元素):(name,type_code,display_size,internal_size,precision,scale,null_ok)其中name, type_code是必须的。lastrowid        返回最后更新行的ID(可选),如果数据库不支持,返回None__iter__()        创建迭代对象(可选,参考next())messages          游标执行好数据库返回的信息列表(元组集合)rownumber         当前结果集中游标的索引(从0行开始)setinput-size(sizes)   设置输入最大值setoutput-size(sizes[,col])  设置列输出的缓冲值 三、代码(1) mysql_1.py[python] view plain copyimport MySQLdb    try:      conn = MySQLdb.connect(host='localhost', user='root', passwd='mysql', db='testdb') # 默认port可以不写3306      cursor = conn.cursor()      sql = "insert into table1 values('105', 'tomy', 23, 'm', 'U.KK.')"      cursor.execute(sql)      conn.commit()    #提交事务commit()      cursor.execute("select * from table1")      results = cursor.fetchall()      for re in results:          print re      cursor.close()      conn.close()  except MySQLdb.Error, e:      conn.rollback()   #回滚rollback()      print "MySQL Error %d: %s" % (e.args[0], e.args[1])  print e  (2) mysql_2.py[python] view plain copy# -*-encoding: utf-8 -*-  import os  import string  import sys  import MySQLdb    # 连接数据库  try:         conn = MySQLdb.connect(host='localhost',port=3306, user='root', passwd='mysql', db='testdb')  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)  print "success create table test1!"    # 插入数据  sql = "insert into test1(name, age) values('%s', '%d')" % ("denny", 23)  try:      cursor.execute(sql)      conn.commit()  #凡是insert,update,delete都要"提交事务commit()",否则数据库不会改变      print "succeess insert a record!"  except Exception, e:      conn.rollback()  #异常必须回滚rollback()      print e  # 插入多条数据  sql = "insert into test1(name, age) values (%s, %s)"  param = (("tom", 24), ("alice", 25), ("bob", "26"))  try:      cursor.executemany(sql, param) #批量插入数据时必须用.executemany(sql)而不是.execute(sql),那是单条数据      conn.commit()      print "success insert many records!"  except Exception, e:      conn.rollback()      print e    # 查询出数据  sql = "select * from test1"  cursor.execute(sql)  alldata = cursor.fetchall()  # 如果有数据返回就循环输出,alldata是个二维列表)  if alldata:      for rec in alldata:          print rec[0], rec[1]  # 分别输出,结果为denny 23          # print rec    # 也可以直接输出rec,不带下标rec[i], 结果为('denny', 23L)    # 关闭连接  cursor.close()  conn.close()  控制台输出结果:SQL表结果:(3) mysql_3.py (fetchone()示例)[python] view plain copyimport MySQLdb    db = MySQLdb.connect("localhost", "root", "mysql", "testdb" )  cursor = db.cursor()  cursor.execute("select * from test1")  data = cursor.fetchone()  while data!=None:      print data[1]      data = cursor.fetchone()  db.close  (4) mysql_4.py(fetchall()示例)[python] view plain copyimport MySQLdb    db = MySQLdb.connect("localhost", "root", "mysql", "testdb" )  cursor = db.cursor()  cursor.execute("select * from test1")  datas = cursor.fetchall()  for data in datas:      print data[1]  print cursor.rowcount,"rows in tatal"  db.close  

0 0
原创粉丝点击