def main():
    table_name = sys.argv[1]
    corpus = ReviewCorpus.load("model/" + table_name)

    read_con = MySQLdb.connect(
        host=DB_SERVER, port=DB_SERVER_PORT, user=DB_USER, passwd=DB_PASSWORD, db=DB_NAME, charset="utf8mb4"
    )
    write_con = MySQLdb.connect(
        host=DB_SERVER, port=DB_SERVER_PORT, user=DB_USER, passwd=DB_PASSWORD, db=DB_NAME, charset="utf8mb4"
    )

    read_cursor = read_con.cursor()
    read_cursor.execute(SQL_QUERY % (table_name))

    write_cursor = write_con.cursor()

    for _ in range(read_cursor.rowcount):
        record = read_cursor.fetchone()
        hotel_review = format_review(record[1])
        tfidf_score = 0
        if hotel_review:
            tfidf_score = corpus.tfidf_score(hotel_review)

        write_cursor.execute(SQL_UPDATE % (table_name, tfidf_score, record[0]))
        write_con.commit()
        print "[%f]%s" % (tfidf_score, record[1])

    write_cursor.close()
    write_con.close()

    read_cursor.close()
    read_con.close()
 def _open(self, conv='', host='', user='', passwd='', db='', port=0):
     """Open database connection. In case of errors exceptions are thrown."""
     if conv=='':
         self._db = MySQLdb.connect(host, user, passwd, db, port, connect_timeout = DB_TIMEOUT)
     else:
         self._db = MySQLdb.connect(conv=conv, host=host, user=user, passwd=passwd, db=db, port=port, connect_timeout = DB_TIMEOUT)
     self._db.set_character_set('utf8')
Example #3
0
def another_page():
  
    print('anotherpage')
    scoop = {'postername': MySQLdb.escape_string(request.form['postername']),
               'activity': MySQLdb.escape_string(request.form['activity']),
               'rank': request.form['rank']
             
               }
    
    if request.method == 'POST':
        db = utils.db_connect()
        cur = db.cursor(cursorclass=MySQLdb.cursors.DictCursor)
        
        query = "INSERT INTO club_name (postername) VALUES ('" + MySQLdb.escape_string(request.form['postername']) + "')"
        # Print query to console (useful for debugging)
        print query
        cur.execute(query)
        id=cur.lastrowid
        #db.commit()
        
        query2 = "INSERT INTO activity (club_id, activity, rank) VALUES (" + str(id) + ", '" + MySQLdb.escape_string(request.form['activity']) + "', '" + request.form['rank'] + "')"
        # Print query to console (useful for debugging)
        print query2
        cur.execute(query2)
        db.commit()
        
        
    cur.execute('SELECT DISTINCT cn.postername, a.activity, a.rank FROM club_name cn NATURAL JOIN activity a')
    rows = cur.fetchall()

    return render_template('another_page.html', club_name=rows, activity = rows, scoop = scoop)
Example #4
0
def index(req):
    send = []
    post_data = str(req.form.list)[8:-7]

    if(post_data[0] == 'R'):
        generateStandard()
        db = MySQLdb.connect("localhost", "erik", "erik", db_name)
        cursor = db.cursor()
        cursor.execute("SELECT DISTINCT(user_id) FROM {}".format(table_name))
        send = cursor.fetchall()
        db.close()

    elif post_data[0] == 'S':
        tmp = post_data.split(',')
        getSubtract(tmp[1], tmp[2])

    else:
        user_id = int(post_data)
        db = MySQLdb.connect("localhost", "erik", "erik", db_name)
        cursor = db.cursor()
        cursor.execute("SELECT image_id, browser FROM {} WHERE user_id='{}'".format(table_name, user_id))
        data = cursor.fetchall()
        db.close()
        generatePictures(data, user_id)
        send = gen_hash_codes(data)


    send_string = json.dumps(send)
    return send_string
Example #5
0
    def get_qsyk_and_insert(self, docid):
        cover_img = MySQLdb.escape_string(docid['cover_img'])
        docid = docid['docid']

        if self.db_has_exist(docid):
            return

        url = "http://c.3g.163.com/nc/article/%s/full.html" % str(docid)
        data = utils.download_page(url, True)

        if data:
            data = data[docid]
            if data:
                ptime = data['ptime']
                today = ptime.split(' ')[0]
                imgs = data['img']
                body = data['body'].encode('utf-8')

                title = data['title'].replace(' ', '').replace('(', '-').replace('(', '-').replace(')', '').replace(')', '')

                for img in imgs:
                    body = body.replace(img['ref'], "<img src=\"" + img['src'] + "\"/><hr>")

                body = body.replace('%', '%%')
                body = MySQLdb.escape_string(body)
                sql = "insert into wangyi(item_type, title, url, docid, cover_img, ptime, today, body) values('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')" % (self._item_type, title, url, docid, cover_img, ptime, today, body)
                utils.insert_mysql(sql)
Example #6
0
def main():
    
    conn = MySQLdb.connect (host=settings.MYSQL_HOST, user=settings.MYSQL_USER, passwd=settings.MYSQL_PASSWORD, db=settings.MYSQL_DATABASE)
    cursor = conn.cursor()

    TABLES = ['agency', 'calendar', 'calendar_dates', 'fare_attributes','fare_rules','routes','shapes', 'stops', 'stop_times', 'trips']

    for table in TABLES:
        print 'processing %s' % table
        f = open('gtfs/%s.txt' % table, 'r')
        reader = csv.reader(f)
        columns = reader.next()
        for row in reader:
            insert_row = []
            for value in row:
                if not is_numeric(value) or value.find('E') != -1:
                    insert_row.append('"' + MySQLdb.escape_string(value) + '"')
                else:
                    insert_row.append(value)
                    
            insert_sql = "INSERT INTO %s (%s) VALUES (%s);" % (table, ','.join(columns), ','.join(insert_row))  
            cursor.execute(insert_sql)
        
        conn.commit()
    cursor.close ()
    conn.close ()
Example #7
0
def insertSimToDB(pulseseq, params, dec):
    """ create an entry for a Simulation """

    if not mysql:
        return

    entry_ps = repr(pulseseq.seq)
    entry_params = MySQLdb.escape_string(repr(params.__dict__))
    entry_hspace = MySQLdb.escape_string(repr(params.hspace.__dict__))
    entry_dec = MySQLdb.escape_string(repr(dec.__dict__))

    dbx = MySQLdb.connect(user="tiqcspice", passwd="tiqc_cluster1", db="tiqcspice", host="marvin")
    db = dbx.cursor()

    sql = "insert into Simulation (name, pulseseq, params, hspace, decoherence) values ('%s', '%s','%s','%s','%s')" % (
        dec.doSQLname,
        entry_ps,
        entry_params,
        entry_hspace,
        entry_dec,
    )
    try:
        db.execute(sql)
    except Exception, e:
        print "ERROR in sql insertSimToDB:", e
Example #8
0
    def connect(self, charSet=None, dbase=None):
        try:
            if charSet == None and dbase == None:
                return self.__connections.getConnection()

            if dbase == None:
                dbase = self.dbName

            # bit ugly but mysqldb docs dont say what the default value for charset is,
            # then i could just set the default val for charSet 
            if charSet != None:
                con = mdb.connect(
                    self.host,
                    self.user,
                    self.passwd,
                    db=dbase,
                    port=self.port,
                    charset=charSet)
            else:
                con = mdb.connect(
                    self.host,
                    self.user,
                    self.passwd,
                    db=dbase,
                    port=self.port)    

            return con

        except mdb.Error as dbError:
            self.onDBError(dbError)
Example #9
0
def putFBrefs(df,auth=authent_local,blocsz=2000):
    con = mdb.connect(**auth)
    # add as refs table to local db
    vals= [ tuple([ None if pd.isnull(v) else v for v in rw]) for rw in df.values ]
    sql="""INSERT INTO pub(pubid,title,ref,abstract)
            VALUES(
            %s,%s,%s,%s)
            """
    nadds=len(vals)*1.0
    nblocs=int(np.ceil(nadds/blocsz))
    print('Adding to references to local db')
    with con:
        cur=con.cursor()
        
        cur.execute("DROP TABLE IF EXISTS pub")
        cur.execute("""CREATE TABLE pub(
            pubid INT PRIMARY KEY,
            title TEXT, 
            ref TEXT,
            abstract TEXT)
            """)       
    #chunk up to keep from bombing
    c=0
    for i in range(nblocs):
        con = mdb.connect(**auth)
        with con:
            cur=con.cursor()
            if (c+blocsz)>nadds:
                cur.executemany(sql,vals[c:])
            else:
                cur.executemany(sql,vals[c:(c+blocsz)])
            c+=blocsz
    print('Done')
Example #10
0
def save_character(json_data):
    json_dict = simplejson.loads(json_data)
    username = MySQLdb.escape_string(json_dict['username'])
    world_id = MySQLdb.escape_string(json_dict['world_id'])

    # TODO save the character
    return simplejson.dumps({"success": "true"})
Example #11
0
def create_databases(installer_json, config_json):
	db_conf = installer_json['database']
	db = MySQLdb.connect(host="localhost", user=db_conf['user'], passwd=db_conf['pass'])
	cur = db.cursor()

	prefix = installer_json['prefix_name']
	platforms = config_json['platforms']

	sql_path = '../sql/'
	for platform in platforms:
		path = sql_path + platform + '.sql'
		try:
			with open(path):
				db_name = prefix + '_' + platform + '_main'
				print '* Creating ' + platform + ' Database.'

				#Step 1
				cur.execute('CREATE DATABASE IF NOT EXISTS ' + db_name + ' DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci')

				db_platform = MySQLdb.connect(host="localhost", user=db_conf['user'], passwd=db_conf['pass'], db= db_name)
				cur_platform = db_platform.cursor()

				fo = open(path, "r")
				db_script = fo.read()
				fo.close()

				if(db_script != ''):
					cur_platform.execute(db_script)
		except IOError:
			print '*** Warning: Problem creating ' + platform + ' Database.'
Example #12
0
 def criartabela_venda(self):       
     
     if  not os.path.exists('agenciaBeta1.db'):
                 print 'Banco de Dados existente'
         
                 conexao = MySQLdb.connect(self.host,self.user,self.passwd,self.database )
                 print 'Banco de Dados ja instalado'
                 conexao = MySQLdb.connect(host="localhost", user="root",passwd="carros", db="agenciaBeta1")
                 cursor = conexao.cursor()
                 
                 sql = """create table venven(
                          codigovenda int(10) PRIMARY kEY Auto_increment NOT NULL UNIQUE,
                          codigo  varchar(60)       NOT NULL  ,
                          codigoveiculo  varchar(10)  NOT NULL  ,
                          codigovendedor varchar(60) NOT NULL  ,
                          formadepagamento varchar(50) not null,
                          financeira varchar(50)not null,
                          data varchar(20))"""
                 
                 print'l'
                 try:
                  
                         print ' testando 1'      
                         cursor.execute(sql)
                         conexao.commit()
                         
                         print 'testando 2'
                 except MySQLdb.Error, e:
                 
                    if e.args[0] == 1050:                     
                      print  'Tratando o erro'
                 self.addTreeViewCliente() 
Example #13
0
 def criartabela_troca(self):
     if not os.path.exists('agenciaBeta1.db'):
                 print 'Banco de Dados existente troca'
         
                 conexao = MySQLdb.connect(self.host,self.user,self.passwd,self.database )
                 print 'Banco de Dados ja instalado troca'
       #trocar aqui na linha de baixo o db
                 conexao = MySQLdb.connect(host="localhost", user="root",passwd="carros", db="agenciaBeta1")
                 cursor = conexao.cursor()
                 
                 sqlt = """create table trocae(
                           codigotroca int(10) PRIMARY kEY Auto_increment NOT NULL UNIQUE,
                           codigocliente  varchar(60)       NOT NULL  ,
                           codigoveiculo  varchar(10)       NOT NULL  ,
                           codigovendedor varchar(60)       NOT NULL  , 
                           placa varchar(10)       NOT NULL  ,         
                           modelo varchar(60)       NOT NULL  ,
                           marca varchar(60)       NOT NULL  ,
                           ano varchar(60)       NOT NULL  ,
                           proprietario varchar(60)       NOT NULL  ,
                           valor float(10) ,
                           data varchar(20))"""
                 try:
                 #verifica se o database nomeado acima ja foi criado 
                         print '    uuuu    troca'      
                     
                         cursor.execute(sqlt)
                         conexao.commit()
                         print 'trocado'
                 except MySQLdb.Error, e:
                 
                    if e.args[0] == 1150:                     
                      print  'Tratando o erro'
                 self.addTreeViewCliente() 
Example #14
0
def getQiubaiDb(password='-'):
    setDelimiter('try database connect')
    userName='root'
    hostName='114.215.108.67'
    dbName='test'
    portName=3306
    try:
        conn=mydb.connect(host=hostName,user=userName,passwd=password,db=dbName,port=portName)
    except mydb.OperationalError:
        while True:
            password=raw_input('password for %s:'%userName)
            try:
                conn=mydb.connect(host=hostName,user=userName,passwd=password,db=dbName,port=portName)
                break
            except mydb.OperationalError:
                continue
    curs=conn.cursor()
    searchDbSql='SELECT * FROM qiubai'
    try:
        curs.execute(searchDbSql)
    except:
        setDelimiter('no DB qiubai found')
        setQiubaiDb(curs)
    setDelimiter('database well connect')
    return (conn,curs)
Example #15
0
def fpost():
    post = MySQLdb.escape_string(smart_str(request.form['post_text']))
    user = MySQLdb.escape_string(smart_str(request.form['user']))
    lv = MySQLdb.escape_string(smart_str(request.form['lvalue']))
    la = MySQLdb.escape_string(smart_str(request.form['ladr']))
    pic = request.files['file']
    if pic:
        ur = secure_filename(pic.filename)
        if '.' not in ur:
            ur = "." + ur
        if len(get_post_all(user)) > 0:
            ur = str(get_post_all(user)[-1][0] + 1) + ur
        else:
            ur = "1" + ur
        pic.save(os.path.join(app.config['UPLOAD_FOLDER'], ur))
        ur = "pics/" + ur
    else:
        ur = "__empty__"
    if posting(user, MySQLdb.escape_string(post), ur):
        if la:
            if la[:7] != "http://":
                la = "http://" + la
            pi = int(get_post_all(user)[-1][0])
            if lv:
                put_link(pi, la, lv)
            else:
                put_link(pi, la)
        session['user'] = user
        return redirect(url_for("hom"))
Example #16
0
def putFBgenerefs(df,auth=authent_local,blocsz=10000):
    con = mdb.connect(**auth)
    # add as gene references table to local db
    vals= [ tuple([ None if pd.isnull(v) else v for v in rw]) for rw in df.values ]
    sql="""INSERT INTO generefs(pubid,FBid,symb)
            VALUES(
            %s,%s,%s)
            """
    nadds=len(vals)*1.0
    nblocs=int(np.ceil(nadds/blocsz))
    print('Adding gene references to local db')
    with con:
        cur=con.cursor()
        
        cur.execute("DROP TABLE IF EXISTS generefs")
        cur.execute("""CREATE TABLE generefs(
            generef_id INT AUTO_INCREMENT PRIMARY KEY,
            pubid INT,
            FBid VARCHAR(50),
            symb VARCHAR(100))
            """)       
    #chunk up to keep from bombing
    c=0
    for i in range(nblocs):
        con = mdb.connect(**auth)
        with con:
            cur=con.cursor()
            if (c+blocsz)>nadds:
                cur.executemany(sql,vals[c:])
            else:
                cur.executemany(sql,vals[c:(c+blocsz)])
            c+=blocsz
    print('Done')
Example #17
0
def redirect_short(short):
    val =  ["shorts.html/" + short]  
    write_log(["V"],request,val)
    if short[len(short)-1] == '_':
        db = MySQLdb.connect(host="localhost", user="ashwin_chandak", passwd="ivB2hnBX",db="ashwin_chandak") # database info
        cur = db.cursor()
        cur.execute("SELECT * FROM clicks WHERE short_id = '%s'" % short[0:len(short)-1])
        short_stats = cur.fetchall()
        return flask.render_template('stats.html',short_url = short[0:len(short)-1], number_clicks = len(short_stats),stats = short_stats)

    # retrieve short string from url
    db = MySQLdb.connect(host="localhost", user="ashwin_chandak", passwd="ivB2hnBX",db="ashwin_chandak") # database info
    db.autocommit(True)
    cur = db.cursor()
    cur.execute("SELECT * FROM links WHERE short = '%s'" % short)

    # redirect if it's exist
    if cur.rowcount > 0:
        results = cur.fetchone()
        long_url= results[2]
        app.logger.debug("redirect to " + long_url)

	#Get IP address and json of geolocationdata, so that latitude and longitude entries can be stored in db
        ip_address = get_ip(request)
        geodata = get_geolocation(ip_address)
        cur.execute("INSERT INTO clicks (`short_id`,`ip_address`,`lat`,`long`) VALUES ('%s','%s',%s,%s)" % ( short,ip_address,geodata.get('latitude','NONE'),geodata.get('longitude','NONE')))
	return redirect(long_url)    
# return 404 if not found
    abort(404)
    def web_db_insert(self,item):
        #     try:
        #         db.insert('t_hh_dianping_tuangou_deal_info',**data)
        #     except:
        #         pass
        key_str = ','.join('`%s`' % k for k in item.keys())
        value_str = ','.join(
            'NULL' if v is None or v == 'NULL' else "'%s'" % MySQLdb.escape_string('%s' % v) for v in
            item.values())
        kv_str = ','.join(
            "`%s`=%s" % (k, 'NULL' if v is None or v == 'NULL' else "'%s'" % MySQLdb.escape_string('%s' % v))
            for (k, v)
            in item.items())
        # print kv_str
        # print key_str

        sql = "INSERT INTO t_hh_dianping_shop_info_pet_hospital(%s) VALUES(%s)" % (key_str, value_str)
        sql = "%s ON DUPLICATE KEY UPDATE %s" % (sql, kv_str)
        print sql
        # with open('eeeeddddd','a') as f:
        #     f.write(sql+'\n')
        # time.sleep(100)
        try:
            db.query(sql.replace('NULL','0'))
        except:
            pass
Example #19
0
 def setUp(self):
     _skip_if_no_MySQLdb()
     import MySQLdb
     try:
         # Try Travis defaults.
         # No real user should allow root access with a blank password.
         self.db = MySQLdb.connect(host='localhost', user='root', passwd='',
                                 db='pandas_nosetest')
     except:
         pass
     else:
         return
     try:
         self.db = MySQLdb.connect(read_default_group='pandas')
     except MySQLdb.ProgrammingError as e:
         raise nose.SkipTest(
             "Create a group of connection parameters under the heading "
             "[pandas] in your system's mysql default file, "
             "typically located at ~/.my.cnf or /etc/.my.cnf. ")
     except MySQLdb.Error as e:
         raise nose.SkipTest(
             "Cannot connect to database. "
             "Create a group of connection parameters under the heading "
             "[pandas] in your system's mysql default file, "
             "typically located at ~/.my.cnf or /etc/.my.cnf. ")
Example #20
0
def upload(upload_rows,table):
    try:
        
        if "adconnect" in table:
            db = mdb.connect(host="localhost", user="root", db='nami_adconnect_backup')
            cur = db.cursor()
            query = "REPLACE INTO `nami_adconnect_backup`.`" + table + """`(`DATE`,`PUB_NAME`,`SOURCE_NAME`,`BUDGET DEPLETED / MISCONFIGURATION`,`DAYPART BLOCK`,`CPIP FILTER`,`GEO FILTER`,`IP BLOCK`,`KEYWORD BLOCK`,`REFERER BLOCK`,`MISSING UA/REF`,`IE USER AGENT FILTER`,`CHROME USER AGENT FILTER`,`FIREFOX USER AGENT FILTER`,`SAFARI USER AGENT FILTER`,`OTHER USER AGENT FILTER`,`MAXQUERY THROTTLE`,`FEED FILTERS/TOLERANCES`,`FEED CALLS`,`TIMEOUTS`,`VALID FEED CALLS`,`CALLS PER QUERY`,`FEED COVERAGE`,`VALID FEED COVERAGE`,`PUBLISHER REQUEST RATIO`,`AD RETURN RATIO`,`AD AVAILABLE RATIO`,`CPC CLIPPED`,`EXCESS ADS`,`PUBLISHER USED LISTINGS`,`PUBLISHER COVERAGE`,`AVG PUBLISHER LISTINGS`,`AVG USED LISTINGS`,`GROSS CLICKS`,
                    `INCOMPLETE URL`,`CLICK TIME FILTER`,`INTERASP FILTER`,`IP MISMATCH`,`UA MISMATCH`,`REFERER MISMATCH`,`CPL FILTER`,`CPQ FILTER`,`CPIP FILTER 2`,`CLICK CAP FILTER`,`COOKIE FILTERED`,`DOMAIN FILTER`,`BACKBUTTON FILTER`,`NO FLASH FILTER`,`OFFSCREEN FILTERED`,`ADVANCED JS FILTERED`,`IFRAME FILTERED`,`TOTAL FILTERED CLICKS`,`ROLLOVER REDIRECT DROPS`,`COOKIE REDIRECT DROPS`,`REFPAGE REDIRECT DROPS`,`JS REDIRECT DROPS`,`TOTAL DROPPED`,`SYSTEM ERRORS`,`TOTAL ERRORS AND DROPS`,`OFFSCREEN`,`ONSCREEN`,`NOSCREEN`,`ROLLOVER CLICKS`,`NON-ROLLOVER CLICKS`,`COOKIE PASS`,`COOKIE FAIL`,`IFRAME PASS`,`IFRAME FAIL`,`ADVANCED JS PASS`,`NATURALPLUS COMPLETE`,`REF ASSIGN JS`,
                    `NATURAL JS`,`COMPLETED REFPAGE`,`FINAL REDIRECT`,`MAX JS NEG PLUS`,`ESTIMATED NET CLICKS`,`GOOD CLICK RATIO`,`ESTIMATED GROSS REVENUE`,`AVG ESTIMATED GROSS CPC`,`ASP ESTIMATED REVENUE`,`ESTIMATED PUBLISHER REVENUE`,`AVG ESTIMATED PUBLISHER CPC`,`ESTIMATED PUBLISHER ECPM`,`VALID NET CLICKS`,`VALID CLICKS PER PUBLISHER USED LISTINGS`,`VALID CLICK RATIO`,`VALID GROSS REVENUE`,`VALID ASP NET REVENUE`,`VALID PUBLISHER NET REVENUE`,`VALID REVENUE RATIO`,`VALID AVG GROSS CPC`,`VALID AVG PUBLISHER CPC`,`VALID PUBLISHER ECPM`) VALUES (%s,
                    %s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"""
        elif "advertiser" in table:
            db = mdb.connect(host="localhost", user="root", db='nami_admanager_backup', port=2000)
            cur = db.cursor()
            query = "REPLACE INTO `nami_admanager_backup`.`" + table + "`(`Date`,`Advertiser`,`Campaign`,`Adgroup`,`Ad`,`Matches`,`Impressions`,`Clicks`,`Conversions`,`Spend`,`Cost`,`CPC`,`Matches_CTR`,`Impressions_CTR`) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s,%s)"

        if len(upload_rows)>1000:
            chunked = chunk(upload_rows,1000)
            for id,row in enumerate(chunked):
                cur.executemany(query,row)
                db.commit()
                print("%s - SUCCESSFULLY INSERTED %s OUT OF %s ROWS INTO DATABASE"%(datetime.now(),len(row),len(upload_rows)))
        else:
            cur.executemany(query,upload_rows)
            db.commit()

        print("%s - SUCCESSFULLY INSERTED %s ROWS INTO DATABASE"%(datetime.now(),len(upload_rows)))

    except:
        print(traceback.print_exc())
Example #21
0
	def __init__(self, dbname,uname,passwd):
		self.__con= MySQLdb.connect('localhost','root', 'root')
		self.__cursor=self.__con.cursor()
		query="show databases"
		self.__cursor.execute(query)
		rows=self.__cursor.fetchall()
		found=False
		for row in rows:
			if (str(row[0])==dbname):
				found=True
				break
		#if the database does not exist create it
		if(found==False):
			query='select user from mysql.user'
			self.__cursor.execute(query)
			rows=self.__cursor.fetchall()
			found=False
			for row in rows:
				if(str(row[0])==uname): 
					found=True
					break
			if(found==False):
				query="create user "+uname+"@localhost identified by '"+passwd+"'"
				self.__cursor.execute(query)
			query='CREATE DATABASE '+str(dbname)
			self.__cursor.execute(query)
			query="GRANT ALL PRIVILEGES ON "+dbname+".* To "+uname+"@localhost"
			self.__cursor.execute(query)
		#close the root connection and connect to the database
		self.__con.close()
		self.__con=MySQLdb.connect('localhost',uname,passwd,dbname)
		self.__cursor=self.__con.cursor()
		self.__con.commit()
		return
Example #22
0
def main():
    
    localfile = 'local.txt'
    with open(localfile) as f:
        g = f.read()
        
    if g == 'True':
        local = True
    else:
        local = False

    if local == False:
        fldr = 'mlb-dfs/'
        serverinfo = security('mysql', fldr)
        con = MySQLdb.connect(host=serverinfo[2], user=serverinfo[0], passwd=serverinfo[1], db='MurrDogg4$dfs-mlb')

    else:
        fldr = ''
        con = MySQLdb.connect('localhost', 'root', '', 'dfs-mlb')            #### Localhost connection
    
    
    gameday = datetime.date.today()
    datestr = datestring(gameday)[1]
    gameList = getSchedule(datestr)
    
    addtoDb(con, gameList, datestr)
        
    return
Example #23
0
    def read_volt(config):
        data = []
        chandata = []

        #Read from DB
        db = MySQLdb.connect("localhost","monitor","1234","smartRectifier")
        curs = db.cursor()
        cmd = "SELECT srVBat FROM sensorDataCurrent ORDER BY srVBat ASC LIMIT 1"
        curs.execute(cmd)
        value = curs.fetchone()
        db.close()
        data.append(value[0])

        #Update data to NULL
        db = MySQLdb.connect("localhost","monitor","1234","smartRectifier")
        curs = db.cursor()
        with db:
            cmd = 'UPDATE sensorDataCurrent SET srVBat = NULL WHERE name = "currentData"'
            curs.execute(cmd)
        db.close()

        for i in range(len(data)):
            chandata.append({"name": "Battery Voltage",
                             "mode": "float",
                             "unit": "Custom",
                             "customunit": "Volt",
                             "LimitMode": 1,
                             "LimitMaxError": 70.0,
                             "LimitMaxWarning": 50.0,
                             "LimitMinWarning": 40.0,
                             "LimitMinError": 30.0,
                             "value": float(data[i])})
        return chandata
Example #24
0
    def connect_to_sql(self, sql_connect, db_name="", force_reconnect=False, create_db=True):
        """
        Connect to SQL database or create the database and connect
        :param sql_connect: the variable to set
        :param db_name: the name of the database
        :param force_reconnect: force the database connection
        :param create_db: create the database
        :return the created SQL connection
        """
        print self
        if sql_connect is None or force_reconnect:
            try:
                sql_connect = MySQLdb.connect(host=config.SQL_HOST, user=config.SQL_USERNAME, passwd=config.SQL_PASSWORD, db=db_name)
                return sql_connect
            except Exception, e:
                # Create the database
                if e[0] and create_db and db_name != "":
                    if sql_connect is None:
                        sql_connect = MySQLdb.connect(host=config.SQL_HOST, user=config.SQL_USERNAME, passwd=config.SQL_PASSWORD)
                    utils.log("Creating database " + db_name)

                    cur = sql_connect.cursor()
                    cur.execute("CREATE DATABASE " + db_name)
                    sql_connect.commit()
                    sql_connect.select_db(db_name)
                    return sql_connect
                else:
                    utils.log("Could not connect to MySQL: %s" % e)
                    return None
Example #25
0
def upload_meta(articleExists, url, title, author, domain, time_pub, text):
	gTime = strftime("%Y-%m-%d %H:%M:%S", gmtime())

	conn = MySQLdb.connect(host="newshub.c5dehgoxr0wn.us-west-2.rds.amazonaws.com",
			user="newshub", passwd="columbiacuj", db="Newshub", charset="utf8")
	cursor = conn.cursor()

	# since we cannot get the author attribute, so we use the word "author" instead
	value = ['', title, author, domain, url, time_pub, gTime, text]
	
	if(articleExists == True):
		cursor.execute("insert into articles values (%s, %s, %s, %s, %s, %s, %s, %s)", value);
	else:
		cursor.execute("insert into deletions values (%s, %s, %s, %s, %s, %s, %s, %s)", value);

	conn.commit()
	cursor.close()
	conn.close()

	if(articleExists == True):
		print "upload an updated article"
	else:
		conn = MySQLdb.connect(host="newshub.c5dehgoxr0wn.us-west-2.rds.amazonaws.com",
				user="newshub", passwd="columbiacuj", db="Newshub", charset="utf8")
		cursor = conn.cursor()

		cursor.execute("delete from articles where URL=%s", url)
		conn.commit()
		cursor.close()
		conn.close()

		print "move a deleted article"
Example #26
0
def signin():
    user = MySQLdb.escape_string(smart_str(request.form['Username']))
    password = MySQLdb.escape_string(smart_str(request.form['Password']))
    if sign_in(user, password):
        posts = fget_post_all(user)
        return render_template("home.html", posts=posts, Username=user)
    return render_template("main-page.html")
Example #27
0
def SaveToken_old(token,typeToken,useruid):#typeToken is 0 for facebook token , 1 for twitter token
	#check if the token is present in the database
        db=MySQLdb.connect(host=HOST,user=DBUSER,passwd=DBPASS,db=DBNAME, use_unicode=True,charset="utf8")
	#db=MySQLdb.connect(HOST,DBUSER,DBPASS,DBNAME)
        cursor=db.cursor(MySQLdb.cursors.DictCursor)
        sql="SELECT count(*) as total FROM accesstoken where accesstoken='"+token+"';"
        rowcount=0
        try:
                queryEsit=cursor.execute(sql)
                results=cursor.fetchall()
                dicti=results[0]
                rowcount=dicti['total']
        except:
                rowcount=0
        cursor.close()
        db.close()
	if rowcount>0:return

	db=MySQLdb.connect(host=HOST,user=DBUSER,passwd=DBPASS,db=DBNAME, use_unicode=True,charset="utf8")
	#db=MySQLdb.connect(HOST,DBUSER,DBPASS,DBNAME)
        cursor=db.cursor(MySQLdb.cursors.DictCursor)
        sql="INSERT INTO accesstoken (accesstoken,type,user_uid) VALUES ('%s',%d,%d);"%(token,typeToken,useruid)
        try:
                cursor.execute(sql)
                db.commit()
        except:
                db.rollback()
	cursor.close()
        db.close()
Example #28
0
def fun():
    user = MySQLdb.escape_string(smart_str(request.form['user']))
    unf = MySQLdb.escape_string(smart_str(request.form['unf']))
    if unfollow(user, unf):
        posts = fget_post_all(user)
        return render_template("home.html", posts=posts, Username=user)
    return render_template("main-page.html")
def open_master_connection():
    """
    Open a connection on the master
    """
    if options.defaults_file:
        conn = MySQLdb.connect(read_default_file = options.defaults_file)
        config = ConfigParser.ConfigParser()
        try:
            config.read(options.defaults_file)
        except:
            pass
        username = config.get('client','user')
        password = config.get('client','password')
        port_number = int(config.get('client','port'))
    else:
        username = options.user
        port_number = options.port
        if options.prompt_password:
            password=getpass.getpass()
        else:
            password=options.password
        conn = MySQLdb.connect(
            host = options.host,
            user = username,
            passwd = password,
            port = options.port,
            unix_socket = options.socket)
    return conn, username, password, port_number
Example #30
0
def run(request):
    PATH_VAR=request.path
    path=PATH_VAR.split('/')    
    path_var=path[1]
    output= None
    status=database_status(path_var)
    if status == "disable":
        p= subprocess.Popen(["/bin/bash","/home/tcs/DEVOPS_MIGRATION/myproject/vm_launch.sh",path_var,' &'], stdout=subprocess.PIPE)
        output, err = p.communicate()
        print output
        cnx = MySQLdb.connect(user='root', passwd="test",db="Devops")
        cur = cnx.cursor()
        cur.execute("update devops_images set status='running' where image_name="+`str(path_var)`)
        cnx.commit()
    elif status == "running":
        p= subprocess.Popen(["/bin/bash","/home/tcs/DEVOPS_MIGRATION/myproject/vm_terminate.sh",path_var], stdout=subprocess.PIPE)
        output, err = p.communicate()
        cnx = MySQLdb.connect(user='root', passwd="test",db="Devops")
        cur = cnx.cursor()
        cur.execute("update devops_images set status='disable' where image_name="+`str(path_var)`)
        cnx.commit()       
    
    t = loader.get_template('click.html')
    files_path=database_path()
#    bashCommand = "sh /home/tcs/test-launch.sh "+path_var
#    os.system(bashCommand)
    if status=="running":
        
        c = RequestContext(request,{'path':path_var,'button_name':'Terminate','test':files_path})
        return HttpResponse(t.render(c))

    else:
        #print "OUTPUT HI"
        c = RequestContext(request,{'path':path_var,'button_name':'Deploy','test':files_path})
        return HttpResponse(t.render(c))