home *** CD-ROM | disk | FTP | other *** search
/ One Click 11 / OneClick11.iso / Bancos de Dados / Conversao / Mysql2Excel / Setup.exe / Mysql2Excel.exe / CompatMysqldb.pyc (.txt) < prev    next >
Encoding:
Python Compiled Bytecode  |  2003-06-23  |  15.1 KB  |  429 lines

  1. # Source Generated with Decompyle++
  2. # File: in.pyc (Python 2.2)
  3.  
  4. '''
  5. Original author: James Henstridge <james@daa.com.au>
  6. Adapted by: Andy Dustman <andy@dustman.net>
  7.  
  8. This is the original Mysqldb.py module which came with MySQLmodule-1.4,
  9. only it has been adapted to use _mysql instead MySQL. It is intended
  10. for backwards compatibility purposes only. But as a bonus, transactions
  11. will work if your database server and table types support them. It is
  12. called CompatMysqldb instead of Mysqldb so as not to interfere with an
  13. existing Mysqldb, or MySQLdb on case-insensitive brain-dead operating
  14. systems.
  15.  
  16. Under no circumstances should you bug James Henstridge about this!!!
  17.  
  18. -----
  19.  
  20. This is a class that implements an interface to mySQL databases, conforming
  21. to the API published by the Python db-sig at
  22. http://www.python.org/sigs/db-sig/DatabaseAPI.html
  23.  
  24. It is really just a wrapper for an older python interface to mySQL databases
  25. called mySQL, which I modified to facilitate use of a cursor.  That module was
  26. Joseph Skinner\'s port of the mSQL module by David Gibson, which was a modified
  27. version of Anthony Baxter\'s msql module.
  28.  
  29. As an example, to add some extra (unprivelledged) users to your database system,
  30. and delete them again:
  31.  
  32. >>> import Mysqldb
  33. >>> conn = Mysqldb.mysqldb(\'mysql@localhost root rootpasswd\')
  34. >>> curs = conn.cursor()
  35. >>> curs.execute("insert into user (host, user) values (\'%s\', \'%s\')",
  36. ... [(\'localhost\', \'linus\'), (\'somewhere.com.au\', \'james\')])
  37. 2
  38. >>> curs.execute("select * from user")
  39. >>> curs.fetchall()
  40.  -- record listing --
  41. >>> curs.execute("delete from user where host = \'somewhere.com.au\' or user = \'linus\'")
  42. 2
  43. >>> curs.close()
  44. >>> conn.close()
  45.  
  46. The argument to mysqldb.mysqldb is of the form \'db@host user pass\',
  47. \'db@host user\', \'db@host\', \'db\', \'db user pass\' or \'db user\'.
  48.  
  49. As always, the source is a good manual :-)
  50.  
  51. James Henstridge <james@daa.com.au>
  52. '''
  53. import _mysql
  54. MySQL = _mysql
  55. from string import upper, split, join
  56. error = 'mysqldb.error'
  57. from MySQLdb.constants import FIELD_TYPE
  58. _type_conv = {
  59.     FIELD_TYPE.TINY: int,
  60.     FIELD_TYPE.SHORT: int,
  61.     FIELD_TYPE.LONG: long,
  62.     FIELD_TYPE.FLOAT: float,
  63.     FIELD_TYPE.DOUBLE: float,
  64.     FIELD_TYPE.LONGLONG: long,
  65.     FIELD_TYPE.INT24: int,
  66.     FIELD_TYPE.YEAR: int }
  67.  
  68. def isDDL(q):
  69.     return upper(split(q)[0]) in ('CREATE', 'ALTER', 'GRANT', 'REVOKE', 'DROP', 'SET')
  70.  
  71.  
  72. def isDML(q):
  73.     return upper(split(q)[0]) in ('DELETE', 'INSERT', 'UPDATE', 'LOAD')
  74.  
  75.  
  76. def isDQL(q):
  77.     return upper(split(q)[0]) in ('SELECT', 'SHOW', 'DESC', 'DESCRIBE')
  78.  
  79.  
  80. class DBAPITypeObject:
  81.     
  82.     def __init__(self, *values):
  83.         self.values = values
  84.  
  85.     
  86.     def __cmp__(self, other):
  87.         if other in self.values:
  88.             return 0
  89.         
  90.         if other < self.values:
  91.             return 1
  92.         else:
  93.             return -1
  94.  
  95.  
  96. _Set = DBAPITypeObject
  97. STRING = _Set(FIELD_TYPE.CHAR, FIELD_TYPE.ENUM, FIELD_TYPE.INTERVAL, FIELD_TYPE.SET, FIELD_TYPE.STRING, FIELD_TYPE.VAR_STRING)
  98. BINARY = _Set(FIELD_TYPE.BLOB, FIELD_TYPE.LONG_BLOB, FIELD_TYPE.MEDIUM_BLOB, FIELD_TYPE.TINY_BLOB)
  99. NUMBER = _Set(FIELD_TYPE.DECIMAL, FIELD_TYPE.DOUBLE, FIELD_TYPE.FLOAT, FIELD_TYPE.INT24, FIELD_TYPE.LONG, FIELD_TYPE.LONGLONG, FIELD_TYPE.TINY, FIELD_TYPE.YEAR)
  100. DATE = _Set(FIELD_TYPE.DATE, FIELD_TYPE.NEWDATE)
  101. TIME = _Set(FIELD_TYPE.TIME)
  102. TIMESTAMP = _Set(FIELD_TYPE.TIMESTAMP, FIELD_TYPE.DATETIME)
  103. ROWID = _Set()
  104.  
  105. class Connection:
  106.     '''This is the connection object for the mySQL database interface.'''
  107.     
  108.     def __init__(self, host, user, passwd, db):
  109.         CLIENT = CLIENT
  110.         import MySQLdb.constants
  111.         kwargs = { }
  112.         kwargs['conv'] = _type_conv
  113.         if host:
  114.             kwargs['host'] = host
  115.         
  116.         if user:
  117.             kwargs['user'] = user
  118.         
  119.         if passwd:
  120.             kwargs['passwd'] = passwd
  121.         
  122.         if db:
  123.             kwargs['db'] = db
  124.         
  125.         
  126.         try:
  127.             self._Connection__conn = apply(MySQL.connect, (), kwargs)
  128.         except MySQL.Error:
  129.             msg = None
  130.             raise error, msg
  131.  
  132.         self._Connection__curs = Cursor(self._Connection__conn)
  133.         self._Connection__transactional = self._Connection__conn.server_capabilities & CLIENT.TRANSACTIONS
  134.  
  135.     
  136.     def __del__(self):
  137.         self.close()
  138.  
  139.     
  140.     def __getattr__(self, key):
  141.         return getattr(self._Connection__curs, key)
  142.  
  143.     
  144.     def __setattr__(self, key, val):
  145.         if key in ('arraysize', 'description', 'insert_id'):
  146.             setattr(self._Connection__curs, key, val)
  147.         else:
  148.             self.__dict__[key] = val
  149.  
  150.     
  151.     def close(self):
  152.         self._Connection__conn = None
  153.  
  154.     
  155.     def cursor(self):
  156.         if self._Connection__conn == None:
  157.             raise error, 'Connection is closed.'
  158.         
  159.         return Cursor(self._Connection__conn)
  160.  
  161.     
  162.     def commit(self):
  163.         '''Commit the current transaction.'''
  164.         if self._Connection__transactional:
  165.             self._Connection__conn.query('COMMIT')
  166.         
  167.  
  168.     
  169.     def rollback(self):
  170.         '''Rollback the current transaction.'''
  171.         if self._Connection__transactional:
  172.             self._Connection__conn.query('ROLLBACK')
  173.         else:
  174.             raise error, 'Not supported by server'
  175.  
  176.     
  177.     def callproc(self, params = None):
  178.         pass
  179.  
  180.     
  181.     def create(self, dbname):
  182.         '''This is not a standard part of Python DB API.'''
  183.         self._Connection__conn.query('CREATE DATABASE %s' % dbname)
  184.         self._Connection__conn.store_result()
  185.         return None
  186.  
  187.     
  188.     def drop(self, dbname):
  189.         '''This is not a standard part of Python DB API.'''
  190.         self._Connection__conn.query('DROP DATABASE %s' % dbname)
  191.         self._Connection__conn.store_result()
  192.         return None
  193.  
  194.     
  195.     def reload(self):
  196.         '''This is not a standard part of Python DB API.'''
  197.         self._Connection__conn.query('RELOAD TABLES')
  198.         self._Connection__conn.store_result()
  199.         return None
  200.  
  201.     
  202.     def shutdown(self):
  203.         '''This is not a standard part of Python DB API.'''
  204.         return self._Connection__conn.shutdown()
  205.  
  206.  
  207.  
  208. class Cursor:
  209.     '''A cursor object for use with connecting to mySQL databases.'''
  210.     
  211.     def __init__(self, conn):
  212.         self._Cursor__conn = conn
  213.         self._Cursor__res = None
  214.         self.arraysize = 1
  215.         self.__dict__['description'] = None
  216.         self._Cursor__open = 1
  217.         self.insert_id = 0
  218.  
  219.     
  220.     def __del__(self):
  221.         self.close()
  222.  
  223.     
  224.     def __setattr__(self, key, val):
  225.         if key == 'description':
  226.             raise error, 'description is a read-only attribute.'
  227.         else:
  228.             self.__dict__[key] = val
  229.  
  230.     
  231.     def __delattr__(self, key):
  232.         if key in ('description', 'arraysize', 'insert_id'):
  233.             raise error, "%s can't be deleted." % (key,)
  234.         else:
  235.             del self.__dict__[key]
  236.  
  237.     
  238.     def close(self):
  239.         self._Cursor__conn = None
  240.         self._Cursor__res = None
  241.         self._Cursor__open = 0
  242.  
  243.     
  244.     def execute(self, op, params = None):
  245.         if not (self._Cursor__open):
  246.             raise error, 'Cursor has been closed.'
  247.         
  248.         if params:
  249.             if type(params[0]) not in (type(()), type([])):
  250.                 params = [
  251.                     params]
  252.             
  253.             if isDDL(op):
  254.                 self.__dict__['description'] = None
  255.                 
  256.                 try:
  257.                     for x in params:
  258.                         self._Cursor__res = self._Cursor__conn.query(op % x)
  259.                     
  260.                     self.insert_id = self._Cursor__res.insert_id()
  261.                 except MySQL.Error:
  262.                     msg = None
  263.                     raise error, msg
  264.  
  265.                 return 1
  266.             
  267.             if isDML(op):
  268.                 self.__dict__['description'] = None
  269.                 af = 0
  270.                 
  271.                 try:
  272.                     for x in params:
  273.                         self._Cursor__res = self._Cursor__conn.query(op % x)
  274.                         af = af + self._Cursor__res.affectedrows()
  275.                     
  276.                     self.insert_id = self._Cursor__res.insert_id()
  277.                 except MySQL.Error:
  278.                     msg = None
  279.                     raise error, msg
  280.  
  281.                 return af
  282.             
  283.             if isDQL(op):
  284.                 
  285.                 try:
  286.                     self._Cursor__res = self._Cursor__conn.query(op % params[-1])
  287.                     self.insert_id = self._Cursor__res.insert_id()
  288.                 except MySQL.Error:
  289.                     msg = None
  290.                     raise error, msg
  291.  
  292.                 self.__dict__['description'] = self._Cursor__res.describe()
  293.                 return None
  294.             
  295.         else:
  296.             
  297.             try:
  298.                 self._Cursor__conn.query(op)
  299.                 self._Cursor__res = self._Cursor__conn.store_result()
  300.                 self.insert_id = self._Cursor__conn.insert_id()
  301.             except MySQL.Error:
  302.                 msg = None
  303.                 raise error, msg
  304.  
  305.             self.__dict__['description'] = None
  306.             if isDDL(op):
  307.                 return 1
  308.             elif self._Cursor__conn.affected_rows() != -1:
  309.                 return self._Cursor__conn.affected_rows()
  310.             else:
  311.                 self.__dict__['description'] = self._Cursor__res.describe()
  312.                 return None
  313.  
  314.     
  315.     def fetchone(self):
  316.         if not (self._Cursor__res):
  317.             raise error, 'no query made yet.'
  318.         
  319.         
  320.         try:
  321.             return self._Cursor__res.fetch_row(1)[0]
  322.         except MySQL.Error:
  323.             msg = None
  324.             raise error, msg
  325.  
  326.  
  327.     
  328.     def fetchmany(self, size = None):
  329.         if not (self._Cursor__res):
  330.             raise error, 'no query made yet.'
  331.         
  332.         
  333.         try:
  334.             if not size:
  335.                 pass
  336.             return self._Cursor__res.fetch_row(self.arraysize)
  337.         except MySQL.Error:
  338.             msg = None
  339.             raise error, msg
  340.  
  341.  
  342.     
  343.     def fetchall(self):
  344.         if not (self._Cursor__res):
  345.             raise error, 'no query made yet.'
  346.         
  347.         
  348.         try:
  349.             return self._Cursor__res.fetch_row(0)
  350.         except MySQL.Error:
  351.             msg = None
  352.             raise error, msg
  353.  
  354.  
  355.     
  356.     def fetchoneDict(self):
  357.         '''This is not a standard part of Python DB API.'''
  358.         if not (self._Cursor__res):
  359.             raise error, 'no query made yet.'
  360.         
  361.         
  362.         try:
  363.             return self._Cursor__res.fetch_row(1, 2)[0]
  364.         except MySQL.Error:
  365.             msg = None
  366.             raise error, msg
  367.  
  368.  
  369.     
  370.     def fetchmanyDict(self, size = None):
  371.         '''This is not a standard part of Python DB API.'''
  372.         if not (self._Cursor__res):
  373.             raise error, 'no query made yet.'
  374.         
  375.         
  376.         try:
  377.             if not size:
  378.                 pass
  379.             return self._Cursor__res.fetch_row(self.arraysize, 2)
  380.         except MySQL.Error:
  381.             msg = None
  382.             raise error, msg
  383.  
  384.  
  385.     
  386.     def fetchallDict(self):
  387.         '''This is not a standard part of Python DB API.'''
  388.         if not (self._Cursor__res):
  389.             raise error, 'no query made yet.'
  390.         
  391.         
  392.         try:
  393.             return self._Cursor__res.fetch_row(0, 2)
  394.         except MySQL.Error:
  395.             msg = None
  396.             raise error, msg
  397.  
  398.  
  399.     
  400.     def setinputsizes(self, sizes):
  401.         pass
  402.  
  403.     
  404.     def setoutputsize(self, size, col = None):
  405.         pass
  406.  
  407.  
  408.  
  409. def mysqldb(connect_string):
  410.     """Makes a connection to the MySQL server.  The Argument should be of
  411. \tthe form 'db@host user pass' or 'db@host user' or 'db@host' or 'db'
  412. \tor 'db user pass' or 'db user', where db is the database name, host
  413. \tis the server's host name, user is your user name, and pass is your
  414. \tpassword."""
  415.     val = split(connect_string)
  416.     if len(val) == 0:
  417.         raise error, 'no database specified'
  418.     
  419.     while len(val) < 3:
  420.         val.append('')
  421.     dh = split(val[0], '@')
  422.     if len(dh) == 0:
  423.         raise error, 'no database specified'
  424.     
  425.     while len(dh) < 2:
  426.         dh.append('')
  427.     return Connection(dh[1], val[1], val[2], dh[0])
  428.  
  429.