Advertisement
Guest User

Untitled

a guest
Sep 17th, 2017
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 4.67 KB | None | 0 0
  1. #!/opt/local/bin/python#
  2. # Template for connecting MySQL from python
  3. #
  4. # Released under the BSD license
  5. #
  6. # Copyright (c) 2009 - 2010, Shlomi Noach
  7. # All rights reserved.
  8. #
  9. # Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
  10. #
  11. #     * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
  12. #     * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
  13. #     * Neither the name of the organization nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission.
  14. #
  15. # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  16. #
  17.  
  18. import getpass
  19. import MySQLdb
  20. from optparse import OptionParser
  21.  
  22. def parse_options():
  23.     usage = "usage: "
  24.     parser = OptionParser(usage=usage)
  25.     parser.add_option("-u", "--user", dest="user", default="", help="MySQL user")
  26.     parser.add_option("-H", "--host", dest="host", default="localhost", help="MySQL host (default: localhost)")
  27.     parser.add_option("-p", "--password", dest="password", default="", help="MySQL password")
  28.     parser.add_option("--ask-pass", action="store_true", dest="prompt_password", help="Prompt for password")
  29.     parser.add_option("-P", "--port", dest="port", type="int", default="3306", help="TCP/IP port (default: 3306)")
  30.     parser.add_option("-S", "--socket", dest="socket", default="/var/run/mysqld/mysql.sock", help="MySQL socket file. Only applies when host is localhost")
  31.     parser.add_option("", "--defaults-file", dest="defaults_file", default="", help="Read from MySQL configuration file. Overrides all other options")
  32.     parser.add_option("-d", "--database", dest="database", help="Database name (required unless query uses fully qualified table names)")
  33.     parser.add_option("-v", "--verbose", dest="verbose", action="store_true", help="Print user friendly messages")
  34.     return parser.parse_args()
  35.  
  36.  
  37. def verbose(message):
  38.     if options.verbose:
  39.         print "-- %s" % message
  40.  
  41. def print_error(message):
  42.     print "-- ERROR: %s" % message
  43.  
  44. def open_connection():
  45.     if options.defaults_file:
  46.         conn = MySQLdb.connect(
  47.             read_default_file = options.defaults_file,
  48.             db = database_name)
  49.     else:
  50.         if options.prompt_password:
  51.             password=getpass.getpass()
  52.         else:
  53.             password=options.password
  54.         conn = MySQLdb.connect(
  55.             host = options.host,
  56.             user = options.user,
  57.             passwd = password,
  58.             port = options.port,
  59.             db = database_name,
  60.             unix_socket = options.socket)
  61.     return conn;
  62.  
  63. def act_query(query):
  64.     """
  65.    Run the given query, commit changes
  66.    """
  67.     connection = conn
  68.     cursor = connection.cursor()
  69.     num_affected_rows = cursor.execute(query)
  70.     cursor.close()
  71.     connection.commit()
  72.     return num_affected_rows
  73.  
  74.  
  75. def get_row(query):
  76.     connection = conn
  77.     cursor = connection.cursor(MySQLdb.cursors.DictCursor)
  78.     cursor.execute(query)
  79.     row = cursor.fetchone()
  80.  
  81.     cursor.close()
  82.     return row
  83.  
  84.  
  85. def get_rows(query):
  86.     connection = conn
  87.     cursor = connection.cursor(MySQLdb.cursors.DictCursor)
  88.     cursor.execute(query)
  89.     rows = cursor.fetchall()
  90.  
  91.     cursor.close()
  92.     return rows
  93.  
  94.  
  95. def exit_with_error(error_message):
  96.     """
  97.    Notify and exit.
  98.    """
  99.     print_error(error_message)
  100.     exit(1)
  101.  
  102.  
  103. try:
  104.     try:
  105.         conn = None
  106.         reuse_conn = True
  107.         (options, args) = parse_options()
  108.  
  109.         database_name = None
  110.  
  111.         if options.database:
  112.             database_name=options.database
  113.  
  114.         conn = open_connection()
  115.  
  116.     except Exception, err:
  117.         print err
  118. finally:
  119.     if conn:
  120.         conn.close()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement