Python MySQLdb.connect() Examples

The following are code examples for showing how to use MySQLdb.connect(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: PythonClassBook   Author: PythonClassRoom   File: DBSetup.py    GNU General Public License v3.0 7 votes vote down vote up
def buildDatabase( databaseName ):

   username = raw_input( "Enter MySQL user name: " )
   password = getpass.getpass( "Enter user password: " )

   print "Creating database %s:" % databaseName

   # retrieve database description from file
   print "\tRetrieving database definition:",

   try:
      databaseDefinition = retrieveDatabaseDefinition( databaseName )
   except TypeError:
      sys.exit( "ERROR\nThe database definition in %s.def is invalid" % databaseName )
   else:
      print "DONE"

   # get a cursor for MySQL
   print "\tConnecting to MySQL:",
   try:
      cursor = MySQLdb.connect( user = username, passwd = password ).cursor()
   except MySQLdb.OperationalError, error:
      sys.exit( "ERROR\nCould not connect to MySQL (%s)" % error ) 
Example 2
Project: petuk.corp   Author: fnugrahendi   File: Garvin.py    GNU General Public License v2.0 6 votes vote down vote up
def GarvinInit(self):
		#-- init dipindah disini, karena dipanggil setelah berhasil login (set database dsb) di fungsi self.Login_Done
		self.DataMaster_init()
		self.BukuBesar_init()
		self.Penjualan_init()
		self.Pembelian__init()
		self.KasBank_init()
		self.Laporan_init()
		
		#--- kalau pindah tab, set semua stackedWidget ke index 0 (suppose to be _Menu index)
		self.tabWidget.setCurrentIndex(0)
		self.tabWidget.currentChanged.connect(self.ResetRooms)
		#--- startup program aswell, stackedwidget room should be on Menu Index 
		self.ResetRooms()
		#--- startup program, set semua datetimeedit ke waktu skrg		
		self.GarvinSetDate(self)
		#~ self.Laporan_BuktiKasKeluar('KK0001')
		#~ self.Laporan_JualBeli('CUSTOMER.00000001',1,'2015-1-1','2015-5-30') 
Example 3
Project: bitmm   Author: thmp   File: coinbase.py    MIT License 6 votes vote down vote up
def __init__(self, orderbook, model, gateway, storage=False, orderbook_usd = None):
        self.orderbook_initialized = False

        self.orderbook = orderbook
        self.orderbook_usd = orderbook_usd

        self.model = model
        self.gateway = gateway

        self.received_full = False

        self.storage = storage
        if storage:
            self.conn = MySQLdb.connect(host="", user="", passwd="", db="")
            self.cur = self.conn.cursor()
            self.count = 0

        self.updateBalance()

        self.processed = 0

        self.ask_set = 0
        self.bid_set = 0

        self.lastOldOrderRemoval = time.time() 
Example 4
Project: ANN   Author: waynezv   File: spider_baidu.py    MIT License 6 votes vote down vote up
def __init__(self):
        Thread.__init__(self)
        self.browser=imitate_browser.BrowserBase()
        self.chance=0
        self.chance1=0
        self.request_queue=Queue()
        self.wait_ana_queue=Queue()
        #self.key_word_queue.put((("动态图", 0, 24)))
        self.count=0
        self.mutex = threading.RLock() #可重入锁,使单线程可以再次获得已经获得的锁
        self.commit_count=0
        self.ID=500
        self.next_proxy_set = set()
        self.dbconn = mdb.connect(DB_HOST, DB_USER, DB_PASS, 'sosogif', charset='utf8')
        self.dbconn.autocommit(False)
        self.dbcurr = self.dbconn.cursor()
        self.dbcurr.execute('SET NAMES utf8') 
Example 5
Project: redditswapbot   Author: thelectronicnub   File: mySQLHandler.py    GNU General Public License v3.0 6 votes vote down vote up
def emit(self, record):
        """
        Connect to DB, execute SQL Request, disconnect from DB
        @param record:
        @return: 
        """ 
        # Use default formatting:
        self.format(record)
        # Set the database time up:
        self.formatDBTime(record)
        if record.exc_info:
            record.exc_text = logging._defaultFormatter.formatException(record.exc_info)
        else:
            record.exc_text = ""
        # Insert log record:
        sql = mySQLHandler.insertion_sql
        try:
            conn=MySQLdb.connect(host=self.db['host'],port=self.db['port'],user=self.db['dbuser'],passwd=self.db['dbpassword'],db=self.db['dbname'])
        except _mysql_exceptions, e:
            from pprint import pprint
            print("The Exception during db.connect")           
            pprint(e)
            raise Exception(e)
            exit(-1) 
Example 6
Project: solar   Author: Mirantis   File: mysql_user.py    Apache License 2.0 6 votes vote down vote up
def connect(module, login_user=None, login_password=None, config_file=''):
    config = {
        'host': module.params['login_host'],
        'db': 'mysql'
    }

    if module.params['login_unix_socket']:
        config['unix_socket'] = module.params['login_unix_socket']
    else:
        config['port'] = module.params['login_port']

    if os.path.exists(config_file):
        config['read_default_file'] = config_file

    # If login_user or login_password are given, they should override the
    # config file
    if login_user is not None:
        config['user'] = login_user
    if login_password is not None:
        config['passwd'] = login_password

    db_connection = MySQLdb.connect(**config)
    return db_connection.cursor() 
Example 7
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 6 votes vote down vote up
def getGenepoolForRecording(recordingID):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()

    sqlcommand = "SELECT genepool FROM recordings where ID=%i" % (recordingID)
    c.execute(sqlcommand)
    data = c.fetchone()

    if data[0] is None:
        return None

    #print data[0]

    return json.loads(data[0]) 
Example 8
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 6 votes vote down vote up
def getGeneticsForRecording(recordingID):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()

    sqlcommand = "SELECT genetics FROM recordings where ID=%i" % (recordingID)
    c.execute(sqlcommand)
    data = c.fetchone()

    if data[0] is None:
        return None

    #print data[0]

    return json.loads(data[0]) 
Example 9
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 6 votes vote down vote up
def getSoundcell(ID):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()

    sqlcommand = "SELECT start,end,events FROM soundcells where ID=%i" % (ID)
    c.execute(sqlcommand)
    data = c.fetchall()

    if data is None:
        return None

    print data

    return data 
Example 10
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 6 votes vote down vote up
def getGenotypesForLineage(lineageID):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "SELECT genotype FROM soundcells where lineageID=%i" % (int(lineageID))
    c.execute(sqlcommand)
    data = c.fetchall()

    if len(data)==0:
        return None

    if data[0][0] is None:
        return None

    genotypes = []

    for genotype in data:
        genotypes.append(json.loads(genotype[0]))

    return genotypes 
Example 11
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 6 votes vote down vote up
def getSequenceIDsForTrack(track):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "SELECT ID,start,end FROM sequences where trackID=%i" % (track[3])
    c.execute(sqlcommand)
    data = c.fetchall()

    if data is None:
        return None

    sequences = []

    for sequence in data:
        sequence = list(sequence)
        sequence.append(track[3])
        sequences.append(sequence)

    return sequences 
Example 12
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 6 votes vote down vote up
def prepareDataForRelations(trackID):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    recordingID = getRecordingIDforTrack(trackID)
    recordingDetails = getRecordingDetails(recordingID)
    recordingTracks = recordingDetails[4]

    genotypes = []
    sequenceData = []

    for track in recordingTracks:
        trackGenotypes = getGenotypesForTrack(track)
        if type(trackGenotypes) <> type(None):
            genotypes.extend(trackGenotypes)
            sequenceData.extend(getSequenceIDsForTrack(track))

    return (genotypes,sequenceData) 
Example 13
Project: cookdevice   Author: Simone-Della   File: cook_device.py    GNU General Public License v3.0 6 votes vote down vote up
def search_ID_in_list_and_connect(search_ID):

  CUR.execute("SELECT Id, Ip, DeviceName, Session FROM %s" % line[7][:-1])
  row = CUR.fetchone()

  while row is not None:
    rows = {row[0] : row[1]}
    type_protocol = row[3]
    row = CUR.fetchone()
    for key in rows.keys():
      if search_ID == key:
        rb1 = str(rows.values())
        ip_device = rb1[2:-2]
        # verify where you try to connect
        print 'Connect to: ' + ip_device
        # condition which protocol use, view in coloumn session in db
        if 'ssh' in type_protocol:
          proto_connections.ssh_connections(ip_device)
        else:
          proto_connections.telnet_connections(ip_device)

  CUR.close()
  CONN.close()

# main function 
Example 14
Project: gthx   Author: gunnbr   File: DbAccess.py    GNU General Public License v2.0 6 votes vote down vote up
def reconnect(self):
        retries = 5
        while True:
            try:
                self.db = MySQLdb.connect(host='localhost', user=self.dbuser, passwd=self.dbpassword, db=self.dbname)
                self.cur = self.db.cursor()
                return
            except MySQLdb.Error, e:
                try:
                    print "Failed to connect. MySQL Error [%d]: %s" % (e.args[0], e.args[1])
                    retries = retries - 1
                    if (retries > 0):
                        print "Waiting to retry (%d)" % retries
                        time.sleep(30)
                    else:
                        raise e
                except IndexError:
                    print "MySQL Error: %s" % str(e)
                    raise e 
Example 15
Project: wikilinks   Author: trovdimi   File: mysqldatabase.py    MIT License 5 votes vote down vote up
def __init__(self, host='localhost', user='wikiwsd', passwd='wikiwsd', database='wikiwsd3'):
        """constructor

           @param host the host to connect to
           @param user the database user
           @param passwd the password to be used in the connection
           @param database the database to select on the server
        """
        self._host = host
        self._user = user
        self._passwd = passwd
        self._database = database 
Example 16
Project: wikilinks   Author: trovdimi   File: mysqldatabase.py    MIT License 5 votes vote down vote up
def _create_connection(self):
        con = mysqldb.connect(self._host, self._user, self._passwd, self._database, charset='utf8', use_unicode=True)
        return con 
Example 17
Project: petuk.corp   Author: fnugrahendi   File: DatabaseCreator.py    GNU General Public License v2.0 5 votes vote down vote up
def Execute(self):
		#~ f = open("creator.md","w")
		#~ f.write(self.sqldump)
		#~ f.close()
		#~ f = open("creator.md","r")
		#~ subprocess.check_call(self.si_om.BasePath[:-1]+"\\mysql\\bin\\mysql.exe --port=44559 -u root test",stdin=f,shell=True)
		#~ f.close()
		#~ subprocess.check_call(self.si_om.BasePath+"mysql/bin/echo.exe < "+"creator.md")
		#~ self.si_om.DatabaseRunQuery(self.sqldump)
		#---- ga bisa pakai runQuery --- commit harus menunggu beberapa detik
		#---- new attempt: exclusive mysqldb
		try:
			self.db = MySQLdb.connect(self.si_om.dbHost,self.si_om.dbUser,self.si_om.dbPass,self.si_om.dbDatabase)
			print ("connected database to generic mysql port")
		except:
			try:
				print "gagal"
				self.db = MySQLdb.Connect(host=self.si_om.dbHost, port=self.si_om.dbPort, user=self.si_om.dbUser, passwd=self.si_om.dbPass, db=self.si_om.dbDatabase)
				print ("connected database to Garvin port")
			except:
				print "gagal"
				#~ exit (1)
		#-- sudah terkoneksi, bentuk cursor
		try:
			self.cursor = self.db.cursor()
		except:return
		self.cursor.execute(self.sqldump)
		self.creatortimer = QtCore.QTimer(self.si_om)
		self.creatortimer.timeout.connect(self.Selesai)
		self.creatortimer.start(4000) 
Example 18
Project: petuk.corp   Author: fnugrahendi   File: Garvin.py    GNU General Public License v2.0 5 votes vote down vote up
def TampilExitButton(self):
		#~ WinW = self.centralwidget.geometry().width()
		#~ WinH = self.centralwidget.geometry().height()
		WinW = 1366
		WinH = 768
		self.tb_Exit =  AnimK.GarvinButtonExit("X",self)
		self.tb_Exit.setObjectName("tb_Exit")
		self.tb_Exit.setText("X")
		self.tb_Exit.setGeometry(QtCore.QRect((WinW-40), 0, 40, 40))
		self.tb_Exit.show()
		self.tb_Exit.clicked.connect(functools.partial(self.DataMaster_Popup,"You sure you want to quit?",self.GarvinQuit)) 
Example 19
Project: petuk.corp   Author: fnugrahendi   File: Garvin.py    GNU General Public License v2.0 5 votes vote down vote up
def initDatabase(self):
		try:
			if str(self.db).find("open")!= (-1):
				return True #-- sudah terkoneksi dan open, skip semua termasuk self.cursor creation
			else:
				raise TypeError("embuh")
		except:
			#-- Belum terkoneksi, koneksikan
			try:
				self.db = MySQLdb.connect(self.dbHost,self.dbUser,self.dbPass,self.dbDatabase)
				print ("connected database to generic mysql port")
			except:
				try:
					print "gagal"
					self.db = MySQLdb.Connect(host=self.dbHost, port=self.dbPort, user=self.dbUser, passwd=self.dbPass, db=self.dbDatabase)
					print ("connected database to Garvin port")
				except:
					print "gagal"
					#~ exit (1)
		#-- sudah terkoneksi, bentuk cursor
		try:
			self.cursor = self.db.cursor()
			return True
		except NameError:return False
		except:return False
		
		#~ try:print "self.db is: "+repr(self.db) +" and its type is: "+str(type(self.db))
		#~ except:pass
		return True 
Example 20
Project: bitmm   Author: thmp   File: hitbtc.py    MIT License 5 votes vote down vote up
def __init__(self, orderbook, model, gateway, storage=False):
        self.orderbook = orderbook
        self.model = model
        self.gateway = gateway

        self.received_full = False

        self.storage = storage
        if storage:
            self.conn = MySQLdb.connect(host= "", user="", passwd="", db="")
            self.cur = self.conn.cursor()
            self.count = 0

        self.updateBalance() 
Example 21
Project: bitmm   Author: thmp   File: storage.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.conn = MySQLdb.connect(host= "", user="", passwd="", db="")
        self.cur = self.conn.cursor()
        self.count = 0 
Example 22
Project: bitmm   Author: thmp   File: database.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.conn = MySQLdb.connect(host="", user="", passwd="", db="")
        self.cur = self.conn.cursor() 
Example 23
Project: redditswapbot   Author: thelectronicnub   File: mySQLHandler.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, db):
        """
        Constructor
        @param db: ['host','port','dbuser', 'dbpassword', 'dbname'] 
        @return: mySQLHandler
        """
        
        logging.Handler.__init__(self)
        self.db = db
        # Try to connect to DB

        # Check if 'log' table in db already exists
        result = self.checkTablePresence()
        # If not exists, then create the table
        if not result:
            try:
                conn=MySQLdb.connect(host=self.db['host'],port=self.db['port'],user=self.db['dbuser'],passwd=self.db['dbpassword'],db=self.db['dbname'])
            except _mysql_exceptions, e:
                raise Exception(e)
                exit(-1)
            else:         
                cur = conn.cursor()
                try:
                    cur.execute(mySQLHandler.initial_sql)
                except _mysql_exceptions as e:
                    conn.rollback()
                    cur.close()
                    conn.close()
                    raise Exception(e)
                    exit(-1)
                else:
                    conn.commit()
                finally:
                    cur.close()
                    conn.close() 
Example 24
Project: redditswapbot   Author: thelectronicnub   File: mySQLHandler.py    GNU General Public License v3.0 5 votes vote down vote up
def checkTablePresence(self):
        try:
            conn=MySQLdb.connect(host=self.db['host'],port=self.db['port'],user=self.db['dbuser'],passwd=self.db['dbpassword'],db=self.db['dbname'])
        except _mysql_exceptions, e:
            raise Exception(e)
            exit(-1) 
Example 25
Project: PythonClassBook   Author: PythonClassRoom   File: fig17_30.py    GNU General Public License v3.0 5 votes vote down vote up
def addAddress( self ):
      """Add address record to database"""

      if self.entries[ "LAST_NAME" ].get() != "" and \
         self.entries[ "FIRST_NAME"].get() != "":

         # create INSERT query command
         query = """INSERT INTO addresses (  
                 FIRST_NAME, LAST_NAME, ADDRESS, CITY,
                 STATE_PROVINCE, POSTAL_CODE, COUNTRY,
                 EMAIL_ADDRESS, HOME_PHONE, FAX_NUMBER
                 ) VALUES (""" + \
                 "'%s', " * 10 % \
                 ( self.entries[ "FIRST_NAME" ].get(),
                   self.entries[ "LAST_NAME" ].get(),
                   self.entries[ "ADDRESS" ].get(),
                   self.entries[ "CITY" ].get(),
                   self.entries[ "STATE_PROVINCE" ].get(),
                   self.entries[ "POSTAL_CODE" ].get(),
                   self.entries[ "COUNTRY" ].get(),
                   self.entries[ "EMAIL_ADDRESS" ].get(),
                   self.entries[ "HOME_PHONE" ].get(),
                   self.entries[ "FAX_NUMBER" ].get() )
         query = query[ :-2 ] + ")"

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query ) 
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
         else:
            cursor.close()
            connection.close()
	    self.clearContents() 
Example 26
Project: PythonClassBook   Author: PythonClassRoom   File: fig17_30.py    GNU General Public License v3.0 5 votes vote down vote up
def findAddress( self ):
      """Query database for address record and display results"""

      if self.entries[ "LAST_NAME" ].get() != "":

         # create SELECT query
         query = "SELECT * FROM addresses " + \
                 "WHERE LAST_NAME = '" + \
                 self.entries[ "LAST_NAME" ].get() + "'"

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query )
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
            self.clearContents()
         else:   # process results
            results = cursor.fetchall()
            fields = cursor.description

            if not results:   # no results for this person
               showinfo( "Not found", "Nonexistent record" )
            else:             # display person's info. in GUI
               self.clearContents()

               # display results
               for i in range( len( fields ) ):

                  if fields[ i ][ 0 ] == "ID":
                     self.IDEntry.set( str( results[ 0 ][ i ] ) )
                  else:
                     self.entries[ fields[ i ][ 0 ] ].insert( 
                        INSERT, str( results[ 0 ][ i ] ) )
            
            cursor.close()
            connection.close() 
Example 27
Project: PythonClassBook   Author: PythonClassRoom   File: fig17_30.py    GNU General Public License v3.0 5 votes vote down vote up
def updateAddress( self ):
      """Update address record in database"""

      if self.entries[ "ID" ].get() != "":

         # create UPDATE query command
         entryItems = self.entries.items()
         query = "UPDATE addresses SET"

         for key, value in entryItems:
            
            if key != "ID":
               query += " %s='%s'," % ( key, value.get() )

         query = query[ :-1 ] + " WHERE ID=" + self.IDEntry.get()

         # open connection, retrieve cursor and execute query
         try:      
            connection = MySQLdb.connect( db = "AddressBook" )
            cursor = connection.cursor()
            cursor.execute( query ) 
         except MySQLdb.OperationalError, message:
            errorMessage = "Error %d:\n%s" % \
               ( message[ 0 ], message[ 1 ] )
            showerror( "Error", errorMessage )
            self.clearContents()
         else:
            showinfo( "database updated", "Database Updated." )
            cursor.close()
            connection.close() 
Example 28
Project: PythonClassBook   Author: PythonClassRoom   File: fig17_29.py    GNU General Public License v3.0 5 votes vote down vote up
def submitQuery( self ):
      """Execute user-entered query agains database"""

      # open connection, retrieve cursor and execute query
      try:      
         connection = MySQLdb.connect( db = "Books" )
         cursor = connection.cursor()
         cursor.execute( self.query.get() )
      except MySQLdb.OperationalError, message:
         errorMessage = "Error %d:\n%s" % \
            ( message[ 0 ], message[ 1 ] )
         showerror( "Error", errorMessage )
         return 
Example 29
Project: chattR   Author: patrickstocklin   File: base.py    GNU General Public License v2.0 5 votes vote down vote up
def get_new_connection(self, conn_params):
        conn = Database.connect(**conn_params)
        conn.encoders[SafeText] = conn.encoders[six.text_type]
        conn.encoders[SafeBytes] = conn.encoders[bytes]
        return conn 
Example 30
Project: turing_bot   Author: gabolaev   File: dbUtils.py    MIT License 5 votes vote down vote up
def execStoreProcedure(procedureName, *args):
    db = MySQLdb.connect(**dbConnection)

    cursor = db.cursor()
    cursor.callproc(procedureName, args)
    result = cursor.fetchall()

    cursor.close()
    db.commit()
    db.close()
    return result 
Example 31
Project: JetPack   Author: dsp-jetpack   File: mysql_db.py    Apache License 2.0 5 votes vote down vote up
def __get_connection__(self):
        return MySQLdb.connect(self.host, self.user,
                               self.passwd, self.db_name) 
Example 32
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def getRecordingDetails(recordingID,printDetails=0):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()

    c.execute("select ID,sessionID,recordingKey,recordingDate from recordings where ID=%i" % (recordingID))
    values = c.fetchone()


    if values==None:
    	raise Exception("No valid ID")

    (recordingID,sessionID,key,date) = values

    if printDetails:
    	print "%i (%s):" % (recordingID,key)

    c.execute("select playerID,audiofile,ID from tracks where recordingID=%i" % (recordingID))
    values = c.fetchall()


    tracks = []

    for track in values:
    	(playerID,audiofile,trackID) = track
    	c.execute("select name,instrument,t_silence,minGapSize from players where ID="+str(playerID))
    	track = c.fetchone()
    	tracks.append([track[0],track[1],audiofile,trackID,recordingID,playerID,track[2],track[3]])

    	if printDetails:
    		print "    %s (%s): %s" % (track[0],track[1],audiofile)

    c.execute("select sessionDate,sessionKey from sessions where ID="+str(sessionID))
    session = c.fetchone()
    values = [recordingID,session[1],session[0],sessionID,tracks,key,date]


    return values 
Example 33
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def listRecodings(sessionID=None,webservice=0,printDetails=0):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    if sessionID is not None:
        sqlQuery = "select ID from recordings where sessionID=" + str(sessionID)
    else:
        sqlQuery = "select ID from recordings"

    c.execute(sqlQuery)
    values = c.fetchall()

    IDs = []
    recordings = []

    for recordingID in values:
    	recordingDetails = getRecordingDetails(recordingID)

    	if printDetails & (not webservice):
    		print "ID %i: %s on %s:" % (recordingDetails[0],recordingDetails[1],recordingDetails[2])

    	IDs.append(recordingDetails[0])
    	recordings.append(recordingDetails)

    	if printDetails & (not webservice):
    		for track in recordingDetails[4]:
    			print "    %s (%s): %s" % (track[0],track[1],track[2])

    if (webservice):
    	return json.dumps(recordings)

    return IDs 
Example 34
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def updateSoniceventsForTrack(track,sonicevents):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    data = json.dumps(sonicevents)

    sqlcommand = "UPDATE tracks SET sonicevents=%s where ID=%i" % (repr(data),track[3])
    c.execute(sqlcommand)
    db.commit()

    print "Updated %i sonicevents for track %i" % (len(sonicevents),track[3]) 
Example 35
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def updateCellsForTrack(track,cells):
    #clear sequences for track
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "DELETE FROM soundcells where trackID=%i" % (track[3])
    c.execute(sqlcommand)
    db.commit()

    for cell in cells:
        start = cell[0] #sonicevents[sequence[0]]["start"]
        end = cell[1] #sonicevents[sequence[-1]]["end"]
        events = json.dumps(cell)
        sqlcommand = "INSERT INTO soundcells (trackID,start,end,events) values (%i,%i,%i,%s)" % (track[3],start,end,repr(events))
        c.execute(sqlcommand)
        db.commit()

    print "Added %i cells for track %i" % (len(cells),track[3])

# def updateSequencesForTrack(track,sequences,sonicevents):
#     #clear sequences for track
#     sqlcommand = "DELETE FROM sequences where trackID=%i" % (track[3])
#     c.execute(sqlcommand)
#     db.commit()

#     for sequence in sequences:
#         start = sequence[0] #sonicevents[sequence[0]]["start"]
#         end = sequence[1] #sonicevents[sequence[-1]]["end"]
#         events = [] #json.dumps(sequence)
#         sqlcommand = "INSERT INTO sequences (trackID,start,end,events) values (%i,%i,%i,%s)" % (track[3],start,end,repr(events))
#         c.execute(sqlcommand)
#         db.commit()

#     print "Added %i sequences for track %i" % (len(sequences),track[3]) 
Example 36
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def updatePhenotypesForTrack(track,sequences,phenotypes,dbField='phenotype'):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    for i in range(0,len(sequences)):
        events = json.dumps(sequences[i])
        phenotype = json.dumps(phenotypes[i])
        sqlcommand = "UPDATE soundcells SET %s=%s where trackID=%i AND start=%s" % (dbField,repr(phenotype),track[3],sequences[i][0])
        c.execute(sqlcommand)
        db.commit()

    print "Updated %i phenotypes for track %i" % (len(phenotypes),track[3]) 
Example 37
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def updateGenotypesForTrack(track,cellBoundaries,genotypes):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    for i in range(0,len(cellBoundaries)):
        events = json.dumps(cellBoundaries[i])
        genotype = json.dumps(genotypes[i].tolist())
        sqlcommand = "UPDATE soundcells SET genotype=%s where trackID=%i AND start=%s" % (repr(genotype),track[3],cellBoundaries[i][0])
        c.execute(sqlcommand)
        db.commit()

    print "Updated %i genotypes for track %i" % (len(genotypes),track[3]) 
Example 38
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def updateRelationsForTrack(track,sequences,relations):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    for i in range(0,len(relations)):
    	events = json.dumps(sequences[i])
    	relation = json.dumps(relations[i])
        sqlcommand = "UPDATE sequences SET relations=%s where trackID=%i AND events=%s" % (repr(relation),track[3],repr(events))
        c.execute(sqlcommand)
        db.commit()

    print "Updated relations for track %i" % (track[3]) 
Example 39
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def getGenotypesForSoundcell(soundcellID):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "SELECT genotype FROM soundcells where ID=%i" % (int(soundcellID))
    c.execute(sqlcommand)
    data = c.fetchone()

    if data[0] is None:
        return None

    return json.loads(data[0]) 
Example 40
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def getGenotypesForTrack(track):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "SELECT genotype,ID,start,lineageID,fitness FROM soundcells where trackID=%i" % (track[3])
    c.execute(sqlcommand)
    data = c.fetchall()

    if len(data)==0:
    	return None

    if data[0][0] is None:
    	return None

    genotypes = []
    IDs = []
    start = []
    lineages = []
    fitnessValues = []

    for genotype in data:
        genotypes.append(json.loads(genotype[0]))
        IDs.append(int(genotype[1]))
        start.append(genotype[2])
        lineages.append(genotype[3])
        fitnessValues.append(genotype[4])

    return (IDs,genotypes,start,lineages,fitnessValues) 
Example 41
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def getPhenotypesForTrack(track,dbField='phenotypeNormed'):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "SELECT %s,ID,start,end FROM soundcells where trackID=%i" % (dbField,track[3])
    c.execute(sqlcommand)
    data = c.fetchall()

    if len(data)==0:
    	return None

    if data[0][0] is None:
    	return None

    phenotypes = []
    IDs = []
    durations = []


    for phenotype in data:
        phenotypes.append(json.loads(phenotype[0]))
        IDs.append(phenotype[1])
        durations.append(phenotype[3]-phenotype[2])


    return (IDs,phenotypes,durations) 
Example 42
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def getSoniceventsForTrack(track):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "SELECT sonicevents FROM tracks where ID=%i" % (track[3])
    c.execute(sqlcommand)
    data = c.fetchone()

    if data[0] is None:
    	return None

    return json.loads(data[0]) 
Example 43
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def getCellsForTrack(track):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "SELECT * FROM sequences where trackID=%i" % (track[3])
    c.execute(sqlcommand)
    data = c.fetchall()

    if data is None:
        return None

    cells = []

    for cell in data:
        cellObject = []
        print cell
        for cellElement in list(cell):
            if is_json(cellElement):
                cellObject.append(json.loads(cellElement))
            else:
                cellObject.append(cellElement)
        cells.append(cellObject)

    return cells 
Example 44
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def getRecordingIDforTrack(trackID):
    db = MySQLdb.connect(host="localhost",
                     user="genimpro",
                     passwd="genimpropw#2016",
                     db="genimpro")
    c = db.cursor()
    sqlcommand = "SELECT recordingID FROM tracks where ID=%i" % (trackID)
    c.execute(sqlcommand)
    data = c.fetchone()
    return data[0] 
Example 45
Project: genimpro   Author: bastustrump   File: recordings.py    MIT License 5 votes vote down vote up
def getGenome():
    db = MySQLdb.connect(host="localhost",
                 user="genimpro",
                 passwd="genimpropw#2016",
                 db="genimpro")
    c = db.cursor()

    sqlcommand = "SELECT variants,clusterGroups FROM genome order by ID desc LIMIT 1 "
    c.execute(sqlcommand)
    data = c.fetchone()

    return json.loads(data[0]), json.loads(data[1]) 
Example 46
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, dbpath):
        self.dbpath = dbpath
        self.connect = None 
Example 47
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __del__(self):
        if self.connect is not None:
            self.connect.commit()
            self.connect.close() 
Example 48
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _open(self):
        import sqlite3 as sqlite3_mod
        self.connect = sqlite3_mod.connect(self.dbpath)
        self.connect.text_factory = str 
Example 49
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def commit(self):
        if self.connect is not None:
            self.connect.commit() 
Example 50
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def execute(self, sql, args = {}):
        #print sql
        #if len(args) > 0: print args
        if self.connect is None:
            self._open()
        cursor = self.connect.cursor()
        if len(args) == 0:
            cursor.execute(sql)
        else:
            cursor.execute(sql, args)
        return cursor 
Example 51
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __del__(self):
        if self.connect is not None:
            self.connect.commit()
            self.connect.close() 
Example 52
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _open(self):
        if not self.db_exists():
            self._init_database()
        self.connect = MySQLdb.connect(host = self.host, db = self.dbname,
                                       user = self.user, passwd = self.passwd) 
Example 53
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _init_database(self):
        connect = self._connect_root()
        cursor = connect.cursor()
        cursor.execute("create database {0}".format(self.dbname)) 
Example 54
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _connect_root(self):
        return MySQLdb.connect(host = self.host, user = self.user,
                               passwd = self.passwd) 
Example 55
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def db_exists(self):
        connect = self._connect_root()
        cursor = connect.cursor()
        cursor.execute("show databases")
        return self.dbname in [row[0] for row in cursor] 
Example 56
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def commit(self):
        if self.connect is not None:
            self.connect.commit() 
Example 57
Project: LogCausalAnalysis   Author: cpflat   File: db_common.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def execute(self, sql, args = {}):
        #print sql
        #if len(args) > 0: print args
        if self.connect is None:
            self._open()
        cursor = self.connect.cursor()
        if len(args) == 0:
            cursor.execute(sql)
        else:
            cursor.execute(sql, args)
        return cursor 
Example 58
Project: machine-learning   Author: pangrou   File: sqlveryzhun.py    GNU General Public License v3.0 5 votes vote down vote up
def db_con():
    db = MySQLdb.connect("127.0.0.1",""---------"",""---------"",""---------"")
    cursor = db.cursor()
    return db,cursor 
Example 59
Project: machine-learning   Author: pangrou   File: saveToMysql.py    GNU General Public License v3.0 5 votes vote down vote up
def db_con_save():
    db = MySQLdb.connect("127.0.0.1",""---------"",""---------"",""---------"")
    cursor = db.cursor()
    return db,cursor 
Example 60
Project: cookdevice   Author: Simone-Della   File: cook_device.py    GNU General Public License v3.0 5 votes vote down vote up
def banner():
  print YELLOW,'Cook Device v1.0\r'
  print '','Search and connect to the device\r'
  print RESET,'\r'

# Function search in database mysql 
Example 61
Project: autopython   Author: wing324   File: rename_mysql_database.py    GNU General Public License v3.0 5 votes vote down vote up
def conn_mysql():
	verbose("Connecting to MySQL......")
	if args.prompt_password:
		password=getpass.getpass("Please input your MySQL password:")
	else:
		password = args.password
	conn = MySQLdb.connect(user=args.user,host=args.host,port=args.port,unix_socket=args.socket,passwd=args.password,db=args.old_database,cursorclass=MySQLdb.cursors.DictCursor)
	return conn
	# 建立MySQL连接
	# connect to MySQL 
Example 62
Project: dbpy   Author: whiteclover   File: connection.py    GNU General Public License v2.0 5 votes vote down vote up
def connect(self):
        self.close()
        self._connect = MySQLdb.connect(**self._db_options)
        self._connect.autocommit(True) 
Example 63
Project: dbpy   Author: whiteclover   File: connection.py    GNU General Public License v2.0 5 votes vote down vote up
def ensure_connect(self):
        if not self._connect or self._max_idle < (time.time() - self._last_used):
            try:
                self._connect.ping()
            except:
                self.connect()
        self._last_used = time.time() 
Example 64
Project: dracon   Author: xcme   File: dracon.py    GNU General Public License v2.0 5 votes vote down vote up
def GetLastConfigFromMySQL(target):
    # По умолчанию конфиг пустой
    last_conf = ''
    try:
	# Пробуем подключиться к базе данных MySQL. Используем таймаут в 2 секунды
        db_conn = MySQLdb.connect(host = mysql_addr_w, user = mysql_user_w, passwd = mysql_pass_w, db = mysql_base_w, connect_timeout = 2)
	db_conn.autocommit(True)
    except MySQLdb.Error as err:
	# Если возникла ошибка при подключении, сообщаем об этом в лог
        logger.info("ERROR: MySQL Error (%s): %s", mysql_addr_w, err.args[1])
    else:
	# Если ошибок не было, создаем 'курсор'
        mysql_cr = db_conn.cursor()
	try:
	    mysql_cr.execute("SELECT config FROM {0}.{1} JOIN {0}.{2} ON {1}.hash={2}.hash WHERE {1}.target=INET_ATON('{3}') AND {1}.direction='up' ORDER BY {1}.timestamp DESC LIMIT 1;".format(mysql_base_w, mysql_ttbl_w, mysql_ctbl_w, target))
	except MySQLdb.Error as err:
	    # При ошибке сообщаем в лог
	    logger.info("ERROR: MySQL Query Error: %s", err.args[1])
	else:
	    data = mysql_cr.fetchall()
	    if len(data):
		last_conf = data[0][0]
	finally:
	    db_conn.close()
    return last_conf

# Функция для определения типа передачи, режима передачи, имени файла, номера блока, IP-адреса цели, типа данных и самих данных 
Example 65
Project: sbdspider   Author: onecer   File: pipelines.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.conn=MySQLdb.connect(host=settings.MYSQL_HOST,
                                  user=settings.MYSQL_USER,
                                  passwd=settings.MYSQL_PASS,
                                  db=settings.MYSQL_NAME,
                                  charset='utf8',
                                  use_unicode=True)
        self.curosr = self.conn.cursor() 
Example 66
Project: Graduation_Design-Distributed_Web_Spider   Author: weiyu666   File: pipelines.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.count = 1
        self.conn = MySQLdb.connect(
                host='localhost',
                port=3306,
                user='root',
                #这里填写密码
                passwd='chen960212',
                db='sinaweibo',
                charset='utf8',
                )
        self.cur = self.conn.cursor() 
Example 67
Project: Graduation_Design-Distributed_Web_Spider   Author: weiyu666   File: pipelines.py    MIT License 5 votes vote down vote up
def __init__(self):
        self.count = 1
        self.conn = MySQLdb.connect(
                host='localhost',
                port=3306,
                user='root',
                #这里填写密码
                passwd='chen960212',
                db='sinaweibo',
                charset='utf8',
                )
        self.cur = self.conn.cursor() 
Example 68
Project: database_schema_sync   Author: lyrl   File: MysqlDataBaseConnector.py    MIT License 5 votes vote down vote up
def __init__(self, config):
        self.database = DataBase(config['database'])
        self.__db = MySQLdb.connect(host=config['ip'], user=config['userName'], passwd=config['password'], db=config['database'], connect_timeout=TIME_OUT)
        self.__cursor = self.__db.cursor()

    # 查询字段
    # @ReturnType DataBaseSchemaSync.entity.Field 
Example 69
Project: HomePy   Author: godstale   File: DBHelper.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def connect(self):
        self.db = MySQLdb.connect("localhost",self.username,self.password,self.dbname)
        self.cursor = self.db.cursor() 
Example 70
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: word_embeddings_loader.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, wl, use_DB=False):
        self.embeddings = None
        self.db = None
        self.wl = wl
        self.use_DB = use_DB
        if not use_DB:
            self.embeddings = {}
            with open(path) as f:
                for line in f:
                    data = line.split()
                    word, data = self.__extract_word(data, wl)
                    w_vector = np.asarray(data, dtype='float32')
                    self.embeddings[word] = w_vector
                    assert(wl == w_vector.shape[0])
            if DEBUG:
                print("Finished loading word vectors at {}".format(path))
                print("Known embeddings: {}".format(len(self.embeddings)))
                print("Word vector length: {}\n".format(wl))
        else:
            import MySQLdb
            from scitail.settings import MYSQL_USER, MYSQL_PASSWORD
            from scitail.settings import WE_DB
            self.db = MySQLdb.connect(user=MYSQL_USER,
                                      passwd=MYSQL_PASSWORD,
                                      db=WE_DB,
                                      use_unicode=True, charset='utf8',
                                      init_command='SET NAMES UTF8')
            if DEBUG:
                print("Using MySQL DB for word embeddings\n") 
Example 71
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: word_embeddings_loader.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, wl, use_DB=False):
        self.embeddings = None
        self.db = None
        self.wl = wl
        self.use_DB = use_DB
        if not use_DB:
            self.embeddings = {}
            with open(path) as f:
                for line in f:
                    data = line.split()
                    word, data = self.__extract_word(data, wl)
                    w_vector = np.asarray(data, dtype='float32')
                    self.embeddings[word] = w_vector
                    assert(wl == w_vector.shape[0])
            if DEBUG:
                print("Finished loading word vectors at {}".format(path))
                print("Known embeddings: {}".format(len(self.embeddings)))
                print("Word vector length: {}\n".format(wl))
        else:
            import MySQLdb
            from qa.settings import MYSQL_USER, MYSQL_PASSWORD, WE_DB
            self.db = MySQLdb.connect(user=MYSQL_USER,
                                      passwd=MYSQL_PASSWORD,
                                      db=WE_DB,
                                      use_unicode=True, charset='utf8',
                                      init_command='SET NAMES UTF8')
            if DEBUG:
                print("Using MySQL DB for word embeddings\n") 
Example 72
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: word_embeddings_loader.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, wl, use_DB=False):
        self.embeddings = None
        self.db = None
        self.wl = wl
        self.use_DB = use_DB
        if not use_DB:
            self.embeddings = {}
            with open(path) as f:
                for line in f:
                    data = line.split()
                    word, data = self.__extract_word(data, wl)
                    w_vector = np.asarray(data, dtype='float32')
                    self.embeddings[word] = w_vector
                    assert(wl == w_vector.shape[0])
            if DEBUG:
                print("Finished loading word vectors at {}".format(path))
                print("Known embeddings: {}".format(len(self.embeddings)))
                print("Word vector length: {}\n".format(wl))
        else:
            import MySQLdb
            from nlp_inference.settings import MYSQL_USER, MYSQL_PASSWORD
            from nlp_inference.settings import WE_DB
            self.db = MySQLdb.connect(user=MYSQL_USER,
                                      passwd=MYSQL_PASSWORD,
                                      db=WE_DB,
                                      use_unicode=True, charset='utf8',
                                      init_command='SET NAMES UTF8')
            if DEBUG:
                print("Using MySQL DB for word embeddings\n") 
Example 73
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: word_embeddings_loader.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, wl, use_DB=False):
        self.embeddings = None
        self.db = None
        self.wl = wl
        self.use_DB = use_DB
        if not use_DB:
            self.embeddings = {}
            with open(path) as f:
                for line in f:
                    data = line.split()
                    word, data = self.__extract_word(data, wl)
                    w_vector = np.asarray(data, dtype='float32')
                    self.embeddings[word] = w_vector
                    assert(wl == w_vector.shape[0])
            if DEBUG:
                print("Finished loading word vectors at {}".format(path))
                print("Known embeddings: {}".format(len(self.embeddings)))
                print("Word vector length: {}\n".format(wl))
        else:
            import MySQLdb
            from multinli.settings import MYSQL_USER, MYSQL_PASSWORD
            from multinli.settings import WE_DB
            self.db = MySQLdb.connect(user=MYSQL_USER,
                                      passwd=MYSQL_PASSWORD,
                                      db=WE_DB,
                                      use_unicode=True, charset='utf8',
                                      init_command='SET NAMES UTF8')
            if DEBUG:
                print("Using MySQL DB for word embeddings\n") 
Example 74
Project: AI2-Reasoning-Challenge-ARC   Author: SebiSebi   File: word_embeddings_loader.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, path, wl, use_DB=False, db_name=None):
        self.embeddings = None
        self.db = None
        self.wl = wl
        self.use_DB = use_DB
        if not use_DB:
            self.embeddings = {}
            with open(path) as f:
                for line in f:
                    data = line.split()
                    word, data = self.__extract_word(data, wl)
                    w_vector = np.asarray(data, dtype='float32')
                    self.embeddings[word] = w_vector
                    assert(wl == w_vector.shape[0])
            if DEBUG:
                print("Finished loading word vectors at {}".format(path))
                print("Known embeddings: {}".format(len(self.embeddings)))
                print("Word vector length: {}\n".format(wl))
        else:
            import MySQLdb
            from settings import MYSQL_USER, MYSQL_PASSWORD, WE_DB
            if db_name is None:
                db_name = WE_DB
            self.db = MySQLdb.connect(user=MYSQL_USER,
                                      passwd=MYSQL_PASSWORD,
                                      db=db_name,
                                      use_unicode=True, charset='utf8',
                                      init_command='SET NAMES UTF8')
            if DEBUG:
                print("Using MySQL DB for word embeddings\n") 
Example 75
Project: vulscan   Author: vulscanteam   File: 38-mysql-unauthorized-access.py    MIT License 4 votes vote down vote up
def _verify(self):
        # 调用指纹方法
        result={}
        import MySQLdb

        vul_ip = self.url[7:]
        user=["root","admin","test",]
        password=['123456','admin',"111111",'root','password','123123','123','1','','{user}',
          '{user}{user}','{user}1','{user}123','{user}2016','{user}2015',
          '{user}!','[email protected]!!','qwa123','12345678','test','[email protected]#',
          '123456789','123321','1314520','666666','woaini','fuckyou','000000',
          '1234567890','8888888','qwerty','1qaz2wsx','abc123','abc123456',
          '1q2w3e4r','123qwe','159357','[email protected]','[email protected]','password!',
          '[email protected]!','password1','r00t','system','111111','admin']

        #判断端口是否开放   
        import socket
        sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sk.settimeout(1)
        try:
            sk.connect((vul_ip,3306))
            #print 'Server port is OK!'
        except Exception:
           return self.save_output(result)
        sk.close()
        
        _conn_timeout = 1
        for u in user:
            for p in password:
                try:
                    print p 
                    pwd = p.replace('{user}', u)
                    conn = MySQLdb.connect(vul_ip, u, pwd, 'mysql',connect_timeout=_conn_timeout )
                    conn.close()
                    result['VerifyInfo'] = {}
                    result['VerifyInfo']['URL'] = vul_ip
                    result['VerifyInfo']['Payload'] = u+":"+pwd
                    return self.save_output(result)
                except Exception as e:
                    pass
        return self.save_output(result)
    # 攻击模块 
Example 76
Project: cookdevice   Author: Simone-Della   File: manage_db_cook.py    GNU General Public License v3.0 4 votes vote down vote up
def create_db():
  try:
    print YELLOW,'Wizard creation Database for COOK DEVICE'
    print '','verify you have installed mysql and configured credential for access'
    print '','and verify if service of mysql is running (systemctl status mariadb.service \ mysql.service)'
    print '','or you start the mysql (systemctl start mariadb.service \ mysql.service)\n'
    print RESET

    user = raw_input('user: ')
    password  = getpass.getpass('password: ')
    CONN = MySQLdb.connect(user=user, passwd=password)
    CUR = CONN.cursor()

    # create database
    database = raw_input('create new database: ')
    CUR.execute("CREATE DATABASE %s" % database)
    CUR.fetchone()
    print GREEN,'result: ok, %s' % database
    print RESET

    # use database created
    CUR.execute("USE %s" % database)

    # create table
    table = raw_input('insert new table name: ')
    CUR.execute("CREATE TABLE %s (Id INT NOT NULL AUTO_INCREMENT PRIMARY KEY, DeviceName VARCHAR(32), Ip VARCHAR(16), Session VARCHAR(8))" % table)
    CUR.fetchone()
    print GREEN,'result: ok, %s' % table
    print RESET

    # insert device in table
    path_file = raw_input('import file (.csv): ')
    query = "LOAD DATA LOCAL INFILE"
    query2 = " '%s'" % path_file
    query3 = " INTO TABLE %s FIELDS TERMINATED BY ',' (DeviceName, Ip, Session);\n" % table
    CUR.execute(query + query2 + query3)
    CONN.commit()
    CUR.fetchall()
    print GREEN,'ok, uploaded, %s' % path_file
    print RESET

    CUR.close()
    CONN.close()

  except MySQLdb.Error, e:
    try:
      print YELLOW, "MySQL Error [%d]: %s" % (e.args[0], e.args[1])
      print 'exit', RESET
    except IndexError:
      print YELLOW, "MySQL Error: %s" % str(e), RESET
      print 'exit', RESET

      CUR.close()
      CONN.close()


# Function for insert new item into tables 
Example 77
Project: cookdevice   Author: Simone-Della   File: manage_db_cook.py    GNU General Public License v3.0 4 votes vote down vote up
def list_table_db():
  try:
    print 'List all records of table'

    user = raw_input('user: ')
    password  = getpass.getpass('password: ')
    CONN = MySQLdb.connect(user=user, passwd=password)
    CUR = CONN.cursor()

    print 'Databases found: \n'

    db = ("SHOW DATABASES")
    CUR.execute(db)
    response_db_list = CUR.fetchall()

    for row in response_db_list:
      print BRIGHT,'-',row[0]
    print RESET # reset color text

    print ''

    database  = raw_input('database: ')
    CUR.execute("USE %s" % database)

    print 'table found in %s : \n' % database
    tables = ("SHOW TABLES")
    CUR.execute(tables)
    response_tables_list = CUR.fetchall()

    for row in response_tables_list:
      print BRIGHT,'-',row[0]
    print RESET

    print ''

    table = raw_input('table: ')

    print 'records in %s: ' % table
    data = ("SELECT * FROM %s" % table)
    CUR.execute(data)
    response_tables_all_data = CUR.fetchall()

    for row in response_tables_all_data:
      print GREEN,'-',row[0],'-', row[1],'-', row[2],'-', row[3]
    print RESET

    CUR.close()
    CONN.close()

  except MySQLdb.Error, e:
    try:
      print YELLOW, "MySQL Error [%d]: %s" % (e.args[0], e.args[1]), RESET
    except IndexError:
      print YELLOW, "MySQL Error: %s" % str(e), RESET

      CUR.close()
      CONN.close()


# delete row in database table 
Example 78
Project: cookdevice   Author: Simone-Della   File: manage_db_cook.py    GNU General Public License v3.0 4 votes vote down vote up
def delete_full_database():
  try:
    print "Delete the full Database from MySQL"

    user = raw_input('user: ')
    password  = getpass.getpass('password: ')
    CONN = MySQLdb.connect(user=user, passwd=password)
    CUR = CONN.cursor()

    print 'Databases found: \n'

    db = ("SHOW DATABASES")
    CUR.execute(db)
    response_db_list = CUR.fetchall()

    for row in response_db_list:
      print BRIGHT,'-',row[0],RESET
    print ''

    database = raw_input("Database: ")

    for line in response_db_list:
      data = re.search(database, str(line))
      if data:
        data.group(0)
        CUR.execute("DROP DATABASE %s;" % database)
        CUR.fetchall()
        CONN.commit()

    print RED,'deleted', RESET
    print ''

    db = ("SHOW DATABASES")
    CUR.execute(db)
    response_db_list = CUR.fetchall()

    for row in response_db_list:
      print BRIGHT,'-',row[0],RESET
    print ''

    CUR.close()
    CONN.close()

  except MySQLdb.Error, e:
    try:
      print YELLOW,"MySQL Error [%d]: %s" % (e.args[0], e.args[1]), RESET
    except IndexError:
      print YELLOW,"MySQL Error: %s" % str(e), RESET

      CUR.close()
      CONN.close()


# Main function 
Example 79
Project: dracon   Author: xcme   File: dracon.py    GNU General Public License v2.0 4 votes vote down vote up
def GetDataFromDB():
    # Значения данных по умолчанию
    devices_data = [ ('0.0.0.0', 0, ''   ) ]
    ports_data   = [ ('0.0.0.0', 0, 0, '') ]
    # Пробуем подключиться к базе данных PostgreSQL либо MySQL. Используем таймаут в 2 секунды
    try:
	if use_postgresql == True:
	    db_conn = psycopg2.connect( host = postgresql_addr, user = postgresql_user, password = postgresql_pass, dbname = postgresql_base, connect_timeout = 2 )
	else:
	    db_conn = MySQLdb.connect( host = mysql_addr, user = mysql_user, passwd = mysql_pass, db = mysql_base, connect_timeout = 2 )
    # Если возникла ошибка при подключении, сообщаем об этом в лог и возвращаем 'пустые' данные
    except psycopg2.Error as p_err:
	logger.info("ERROR: PostgreSQL Error (%s): %s", postgresql_addr, p_err.args)
	return devices_data, ports_data
    except MySQLdb.Error as m_err:
	logger.info("ERROR: MySQL Error (%s): %s", mysql_addr, m_err.args[1])
	return devices_data, ports_data
    # Если ошибок не было, сообщаем в лог об успешном подключении и создаем 'курсор'
    else:
	if use_postgresql == True:
	    logger.info("INFO: Connection to PostgreSQL Server '%s' established", postgresql_addr)
	else:
	    logger.info("INFO: Connection to MySQL Server '%s' established", mysql_addr)
	db_cr = db_conn.cursor()
	# Пробуем выполнить запрос к базе и получить все данные из 'курсора' (списоки устройств и портов)
	try:
	    db_cr.execute(devices_query)
	    devices_data = db_cr.fetchall()
	    db_cr.execute(ports_query)
	    ports_data = db_cr.fetchall()
	# Если возникла ошибка при выполнении запроса, сообщаем об этом в лог и возвращаем 'пустые' данные
	except psycopg2.Error as p_err:
	    logger.info("ERROR: PostgreSQL Query failed: %s", p_err.args)
	    return devices_data, ports_data
	except MySQLdb.Error as m_err:
	    logger.info("ERROR: MySQL Query failed: %s", m_err.args[1])
	    return devices_data, ports_data
	# Если ошибок не возникло, сообщаем в лог об успешном подключении
        else:
	    if use_postgresql == True:
		logger.info("INFO: PostgreSQL Query OK. %s rows found for devices and %s for ports", len(devices_data), len(ports_data))
	    else:
		logger.info("INFO: MySQL Query OK. %s rows found for devices and %s for ports", len(devices_data), len(ports_data))
	# Закрываем подключение
	finally:
	    db_conn.close()
    # Возвращаем списки портов и устройств
    return devices_data, ports_data

# Функция размещения полученной конфигурации в базе MySQL 
Example 80
Project: dracon   Author: xcme   File: dracon.py    GNU General Public License v2.0 4 votes vote down vote up
def PutConfigToMySQL(direction, cfg, target, name, switch, ip, m5d, cfg_type):
    # Сортируем и склеиваем блоки данных
    cfg = ''.join([cfg[i] for i in sorted(cfg.keys())])
    # Формируем данные для размещения их в базе
    mysql_query = "INSERT INTO {0}.{1} ({1}.timestamp, {1}.ip, {1}.target, {1}.direction, {1}.switch, {1}.name, {1}.hash) VALUES ".format(mysql_base_w, mysql_ttbl_w)
    mysql_query+= "('{0}', INET_ATON('{1}'), INET_ATON('{2}'), '{3}', '{4}', '{5}', '{6}');".format(GetDTTM()[0], ip, target, direction, switch, name, m5d)
    # Пробуем подключиться к базе данных MySQL. Используем таймаут в 2 секунды
    try:
	db_conn = MySQLdb.connect(host = mysql_addr_w, user = mysql_user_w, passwd = mysql_pass_w, db = mysql_base_w, connect_timeout = 2)
	db_conn.autocommit(True)
    # Если возникла ошибка при подключении, сообщаем об этом в лог
    except MySQLdb.Error as err:
        logger.info("ERROR: MySQL Error (%s): %s", mysql_addr_w, err.args[1])
    # Если ошибок не было, создаем 'курсор'
    else:
        mysql_cr = db_conn.cursor()
	# Пробуем записать в базу информацию об операции
	try:
	    mysql_cr.execute(mysql_query)
	# При ошибке выполнения запроса сообщаем в лог о проблеме
	except MySQLdb.Error as err:
	    logger.info("ERROR: MySQL Query Error: %s", err.args[1])
	else:
	    # Помещать в базу данных следует только саму конфигурацию, потому что бэкапы там уже есть, а ПО не должно быть вообще
	    if cfg_type == 'config':
		# Пробуем выполнить запрос к базе и подсчитать кол-во уникальных записей для hash
		try:
		    mysql_cr.execute("SELECT COUNT(*) FROM {0}.{1} WHERE {1}.hash='{2}'".format(mysql_base_w, mysql_ctbl_w, m5d))
		# При ошибке выполнения запроса сообщаем в лог о проблеме
		except MySQLdb.Error as err:
		    logger.info("ERROR: MySQL Query Error: %s", err.args[1])
		else:
		    hash_count = mysql_cr.fetchall()[0][0]
		    # Определяем, является ли данный hash уникальным
		    unique_hash = (hash_count == 0)
		    # Если hash уникален (еще не встречался), записываем конфиг в базу
		    if unique_hash:
			try:
			    mysql_cr.execute("INSERT INTO {0}.{1} ({1}.hash, {1}.config) VALUES ('{2}', '{3}');".format(mysql_base_w, mysql_ctbl_w, m5d, cfg))
			# При ошибке выполнения запроса сообщаем в лог о проблеме
			except MySQLdb.Error as err:
			    logger.info("ERROR: MySQL Query Error: %s", err.args[1])
			# Либо сообщаем об успешной операции записи
			else:
			    logger.info("INFO: Succesfully sent %s bytes to MySQL for '%s' ('%s'). Request from %s", len(cfg), target, switch, ip)
	finally:
	    db_conn.close()

# Функция получения последней конфигурации из базы MySQL