def create_search_table(db_info, table_name): connector = mysql.connector.connect( auth_plugin='mysql_native_password', host=db_info["host"], user=db_info["user"], passwd=db_info["passwd"], db=db_info["db_name"], ) cursor = connector.cursor() sql = """ CREATE TABLE IF NOT EXISTS %s( id BIGINT PRIMARY KEY AUTO_INCREMENT, user_id VARCHAR(50) unique not null, name VARCHAR(50), screen_name VARCHAR(50), location VARCHAR(50), description TEXT, latest_tweet_text TEXT, latest_tweet_created_at DATETIME ) ; """ % (table_name) cursor.execute(sql) connector.commit() cursor.close() connector.close()
def login(): if request.method == "POST": playerid = request.form['playerid'] connector = mysql.connector.connect(host='localhost', user='******', database='flexplay') if connector.is_connected(): cursor = connector.cursor() query = 'SELECT groupid, admin FROM player_groups WHERE playerid = "' + playerid + '"' cursor.execute(query) groups = cursor.fetchall() if groups is not None: player_groups = {} for group in groups: query = 'SELECT groupname FROM group_master WHERE groupid = "' + group + '"' cursor.execute(query) group_name = cursor.fetchone() player_groups[group] = group_name cursor.close() connector.close() return jsonify({'groups': player_groups})
def group_event_home(): if request.method == "POST": eventid = request.form['eventid'] connector = mysql.connector.connect(host='us-cdbr-east-02.cleardb.com', user='******', password='******', database='heroku_26cfe5af0cd58f4') if connector.is_connected(): cursor = connector.cursor(buffered=True) query = 'SELECT * FROM events_players WHERE creater = "' + eventid + '"' cursor.execute(query) event_players = cursor.fetchall() cursor.close() connector.close() players = [] for player in event_players: players.append({ 'username': player[0], 'firstname': player[1], 'lastname': player[2] }) return jsonify({'players': players})
def insert(self, data): try: connector = self.connect_mysql() cursor = connector.cursor() add_shorten_url = ( "insert into url_shortening " "(id, alias, url, full_url) " "values (%(id)s, %(alias)s, %(url)s, %(full_url)s)") cursor.execute(add_shorten_url, data) # Make sure data is committed to the database connector.commit() except KeyError as error: return self.createDataError("KEY ALREADY EXISTS", data['alias'], "002") except Exception as e: print(e) return self.createDataError("ERROR TO INSERT URL SHORTENING", data['alias'], "003") finally: cursor.close() connector.close() return data
def find_nagios_hosts(list_of_host_name): print('Check Nagios hosts:') CMDS = [['service', 'mysqld', 'start'], ['service', 'nagios', 'start'], ['service', 'ndo2db', 'start']] for run_command in CMDS: subprocess.call(run_command) try: connector = mysql.connector.connect(db='ndoutils', user='******', password='******') cur = connector.cursor() cur.execute('SELECT display_name, address FROM nagios_hosts') rows = cur.fetchall() for host_name_and_ip in list_of_host_name: result = False for row in rows: if (host_name_and_ip['host'] == row[0] and host_name_and_ip['ip'] == row[1]): print('Host %s: True' % host_name_and_ip['host']) result = True if not result: print('Host %s: False' % host_name_and_ip['host']) finally: cur.close() connector.close()
def oddEven(): pwd = 'rlaehgus1' engine = create_engine('mysql+mysqlconnector://root:' + pwd + '@localhost/lotto', echo=False) connector = engine.connect() df = pd.read_sql("select odd from winlotto WHERE count > 600", con=connector) odd = df.values unique_elements, counts_elements = np.unique(odd, return_counts=True) print("당첨번호 6개중 홀수 번호가 나온 총 갯수") print(np.asarray((unique_elements, counts_elements)), "전체회차 = ", len(odd)) df = pd.read_sql("select even from winlotto WHERE count > 600", con=connector) even = df.values unique_elements, counts_elements = np.unique(even, return_counts=True) print("당첨번호 6개중 짝수 번호가 나온 총 갯수") print(np.asarray((unique_elements, counts_elements)), "전체회차 = ", len(even)) print() plt.figure(figsize=(18, 10)) plt.hist(odd, bins=6) # plt.hist(even, bins=6) connector.close()
def child_cards(self): connector = mysql.connector.connect(**connect_value) cursor = connector.cursor() parent_no = self.no sql = u"select * from cards where parent_no = %s order by no" cursor.execute(sql, (parent_no, )) child_cards = cursor.fetchall() cursor.close() connector.close() return_child_cards = [] for child_card in child_cards: card = Card() card.no = child_card[0] card.attr = child_card[1] card.name = child_card[2] card.image = child_card[3] card.description = child_card[4] card.parent_no = child_card[5] return_child_cards.append(card) return return_child_cards
def handle(): connector = mysql.connector.connect(user=conf.user, database=conf.database, passwd=conf.passwd, host=conf.host, port=conf.port) answer = [] cursor = connector.cursor() # call a stored procedure to get the tags cursor.callproc('get_categories') result = next(cursor.stored_results()) for (category_id, category_name) in result: entry = {} entry['category_name'] = category_name entry['category_id'] = category_id answer.append(entry) connector.close() return json.dumps(answer), status.HTTP_200_OK
def create(self): connector = mysql.connector.connect(**connect_value) cursor = connector.cursor() # 取得できる内容でインサート sql = u"insert into cards (name, image, description, parent_no)values(%s, %s, %s, %s)" cursor.execute( sql, (self.name, self.image, self.description, self.parent_no)) # インサートした際のindexを取得する sql = u"select last_insert_id() from cards limit 1" cursor.execute(sql) ins_no = (cursor.fetchall())[0][0] self.no = ins_no # 取得したindexで画像ファイルをコピー image_name, file_ext = os.path.splitext(self.image) shutil.copyfile("./selectImages/" + self.image, "./images/" + str(ins_no) + file_ext) self.image = str(ins_no) + file_ext # 最初にインサートした内容を取得したindexで更新 # TODO imageカラムをなくす sql = u"update cards set image = %s where no = %s" cursor.execute(sql, (self.image, self.no)) connector.commit() print("-- inserted No:" + str(ins_no) + " --") cursor.close() connector.close() return self
def __init__(self, card_no=0, attr=0, image="_err.jpg", name="No Name", description="・・・・・・", parent_no=0): connector = mysql.connector.connect(**connect_value) cursor = connector.cursor() self.no = card_no self.attr = attr self.name = name self.image = image self.description = description self.parent_no = parent_no if card_no != 0: sql = u"select * from cards where no = %s" cursor.execute(sql, (card_no, )) fetch_card = (cursor.fetchall())[0] self.attr = fetch_card[1] self.name = fetch_card[2] self.image = fetch_card[3] self.description = fetch_card[4] self.parent_no = fetch_card[5] cursor.close() connector.close()
def mysql_close_connection(connector): try: connector.close() except mysql.connector.Error as err: print err else: print "Disconnected from MySQL"
def odbc_close_connection(connector): try: connector.close() except pyodbc.Error as err: print err else: print "Disconnected from MDB"
def insert_into_online_shop(self, topic_cluster, word, score, merchant_name, year, month): connector = self.connector() cursor = connector.cursor() add_data_query = ( "INSERT INTO online_shop " "(id, topic_cluster, word, score, merchant_name, created_at)" "VALUES (%(id)s, %(topic_cluster)s, %(word)s, %(score)s, %(merchant_name)s, %(created_at)s)" ) data = { 'id': str(uuid.uuid4()), 'topic_cluster': topic_cluster, 'word': word, 'score': float(score), 'merchant_name': merchant_name, 'created_at': date(year, month, 1) } try: cursor.execute(add_data_query, data) connector.commit() except mysql.connector.Error: connector.rollback() cursor.close() connector.close()
def create_group(): if request.method == "POST": playerid = request.form["playerid"] groupname = request.form["groupname"] groupid = randint(100000, 999999) connector = mysql.connector.connect( host='localhost', user='******', database='flexplay', auth_plugin='mysql_native_password') if connector.is_connected(): cursor = connector.cursor(buffered=True) query = 'SELECT groupid FROM player_groups' cursor.execute(query) all_groupid = cursor.fetchall() while groupid in all_groupid: groupid = randint(1000000, 9999999) query = "INSERT INTO player_groups (playerid, groupid, admin) VALUES (%s, %s, %s);" val = playerid, groupid, True cursor.execute(query, val) connector.commit() query = "INSERT INTO group_master (groupid, groupname) VALUES (%s, %s)" val = groupid, groupname cursor.execute(query, val) connector.commit() cursor.close() connector.close() return "created group successfully"
def drop(self): connector = mysql.connector.connect(**connect_value) cursor = connector.cursor() if self.no != 0: # 親カードを削除 sql = u"delete from cards where no = %s" cursor.execute(sql, (self.no, )) # 子カードも削除 sql = u"delete from cards where parent_no = %s" cursor.execute(sql, (self.no, )) # ファイルが存在してれば消す いろんな拡張しに対応する必要あり for ext in [ ".jpg", ".jpeg", ".JPG", ".JPEG", ".png", ".PNG", ".gif", ".GIF" ]: if os.path.isfile(os.path.join("./images/", self.no + ext)): os.remove(os.path.join("./images/", self.no + ext)) print("-- deleted No:" + self.no + " --") connector.commit() cursor.close() connector.close()
def authorization(username, password): connector = mysql.connector.connect(host='localhist', user='******', database='flexplay') if connector.is_connected(): cursor = connector.cursor() query = 'SELECT * FROM players_master WHERE username = "******"' cursor.execute(query) Player = cursor.fetchone() cursor.close() connector.close() if Player is not None: player_info = Player columns = ('playerid', 'username', 'firstname', 'lastname', 'email', 'phonenumber', 'groupid', 'teamname', 'password') player_info_tuple = zip(columns, player_info) player = dict(player_info_tuple) if Player is None: response = {'response': 'Player not found'} access = {'access': False} elif not check_password_hash(player["password"], password): response = {'response': 'Incorrect password'} access = {'access': False} elif check_password_hash(player['password'], password): response = player access = {'access': True} return access, response
def handle_details(session_id, item_id): # session_ids are 16 characters long if (len(session_id) > 16): return '', status.HTTP_400_BAD_REQUEST connector = mysql.connector.connect( user=conf.user, database=conf.database, passwd=conf.passwd, host=conf.host, port=conf.port) cursor = connector.cursor() data = request.get_json() if(cursor.callproc('check_user_item_permission', args=[session_id, item_id, 0])[2] == 0): # do stuff cursor.callproc('delete_item_details', args=[item_id]) # add all the details for detail_key, detail_value in data.items(): cursor.callproc('add_item_detail', args=[item_id, detail_key, detail_value, 0]) connector.close() return '', status.HTTP_200_OK else: connector.close() return '', status.HTTP_401_UNAUTHORIZED
def get_data(): # 2、登录数据库 connector = mysql.connector.connect(**config) # **后面加上配置文件名 # 建游标 cursor = connector.cursor(buffered=True) list_1 = {} cur = cursor.execute("select name,phone from aqhy.access_user") # 查看数据库数据 desc = cursor.description # 获取字段的描述,默认获取数据库字段名称,重新定义时通过AS关键重新命名即可 data_dict = [ dict(zip([col[0] for col in desc], row)) for row in cursor.fetchall() ] # 列表表达式把数据组装起来 print(data_dict) # 切记一定要执行 cursor.execute('commit') # 关闭游标 cursor.close() # 关闭连接 connector.close() return data_dict
def analysis_max(): pwd = 'rlaehgus1' engine = create_engine('mysql+mysqlconnector://root:' + pwd + '@localhost/lotto', echo=False) connector = engine.connect() #각 자리수별 뽑힌 숫자들 전체를 조회 for i in range(1, 8): sql = "select `" sql += str(i) sql += "` from winlotto" try: nums = connector.execute(sql) results = nums.fetchall() #해당 숫자의 뽑힌 횟수를 하나씩증가 lottoarray = [0 for i in range(46)] for row in results: k = row[0] count = lottoarray[k] lottoarray[k] = count + 1 print(i, "자리 max count 숫자 =", lottoarray.index(max(lottoarray))) except Exception as err: print(str(err)) connector.close()
def connexion(): connector = None mysql_config = None mysql_config_path = './mysql.ini' try: mysql_config = configparser.ConfigParser() mysql_config.read('flask/mysql.ini') except Exception as e: print(e) try: connector = mysql.connector.connect( host=mysql_config['mysql']['host'], database=mysql_config['mysql']['db'], user=mysql_config['mysql']['user'], password=mysql_config['mysql']['password'], auth_plugin='mysql_native_password') if connector.is_connected(): yield connector except Error as e: print(e) if connector is not None and connector.is_connected: connector.close()
def used_number(count): pwd = 'rlaehgus1' engine = create_engine('mysql+mysqlconnector://root:' + pwd + '@localhost/lotto', echo=False) connector = engine.connect() courrentCount = pd.read_sql("SELECT max(count) FROM winlotto", con=connector) beginCount = courrentCount - count begin = int(beginCount.iloc[0]) used = pd.read_sql( "SELECT `1`,`2`,`3`,`4`,`5`,`6` FROM winlotto WHERE count >= %s" % begin, con=connector) used = np.unique(used) print('조회한 회차수 = ', count) print('사용할 번호는 = ', used) print('사용할 번호 갯수는 = ', len(used)) print() connector.close() return used
def f4(request=None): ''' 与f3相比,使用第三方工具进行模板渲染 需要jinja2的模块 jinja2专门用来做模板渲染 from jinja2 import Template ''' connector = mysql.connector.connect(user='******', password='******', database='py_write') cursor = connector.cursor() cursor.execute( 'SELECT name,score,date FROM db_movie ORDER BY score DESC,date DESC;') movie_list = cursor.fetchall() cursor.close() connector.close() f = open('D:/py/py_django/ep1/dynamic_ep0/movie_f4.html', 'r', encoding='utf-8', errors='ignore') response = f.read() f.close() #把自己的模板放入到Template中 template = Template(response) #进行渲染,得到渲染后的全部html response = template.render(movie_list=movie_list) return response
def sale_by_user(sale): try: connector = Dao.get_connection() cursor = connector.cursor() insert_sale_info = ( "INSERT INTO sale" "(seller_id, startdate, enddate, address_line_one, address_line_two, city, state, country, pincode, start_price)" "VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s)") user_info = (sale.seller_id, sale.startdate, sale.enddate, sale.address_line_one, sale.address_line_two, sale.city, sale.state, sale.country, sale.pincode, sale.start_price) cursor.execute(insert_sale_info, user_info) # Make sure data is committed to the database connector.commit() except DatabaseError as e: print "\nError occurred while creating sale for the user", e try: cursor.close() connector.close() except: print "Error closing connection to database after creating sale record"
def get_bids_for_completed_sales(): connector = Dao.get_connection() cursor = connector.cursor(dictionary=True) query = ("SELECT MAX(bid.bid_price) AS final_bid_price, " "ANY_VALUE(sale.start_price) AS start_price " "FROM bid INNER JOIN sale ON bid.sale_id = sale.id " "WHERE enddate <= %s GROUP BY bid.sale_id") now = datetime.now() cursor.execute(query, (now, )) rows = cursor.fetchall() sales_with_final_bid_list = [] for row in rows: sale_with_final_bid_dict = { "earning": row["final_bid_price"] - row["start_price"] } sales_with_final_bid_list.append(sale_with_final_bid_dict) cursor.close() connector.close() return sales_with_final_bid_list
def user_login(): response.content_type = "application/json" if conn.is_connected: data = {} email = request.json['email'] password = request.json['password'] connector = conn.cursor(buffered = True) query = ("Select * from staff where staff_email ='{}' ").format(email) connector.execute(query) count = connector.rowcount if count > 0: count = 0 for (staff )in connector: data[count] = {} data[count]['staff_id'] =staff[0] data[count]['dept_no'] =staff[1] data[count]['staff_name'] = staff[2] data[count]['staff_password'] = staff[3] data[count]['staff_email'] = staff[4] data[count]['staff_role'] =staff[5] data[count]['staff_avatar'] = staff[6] count +=1 return (data) connector.close() conn.close() return ({'status':False,'Message':'Login failed' })
def get_sale_details(seller_id): # select max(bid_price) as max_price from bid where sale_id=3; connector = Dao.get_connection() cursor = connector.cursor(dictionary=True) query = ("SELECT id, seller_id, startdate, enddate, address_line_one, address_line_two, city, state, country, pincode, start_price" \ " FROM sale where seller_id = %s") cursor.execute(query, (seller_id, )) sales_from_database = cursor.fetchall() sales = {} for row in sales_from_database: sale = Sale(row["seller_id"], row["startdate"], row["enddate"].strftime('%m/%d/%Y'), row["address_line_one"], row["address_line_two"], row["city"], row["state"], row["country"], row["pincode"], row["start_price"]) sales[row['id']] = sale cursor.close() connector.close() ''' { 1 : salesObj1, 2 : salesObj2, 4 : saledObj3 } ''' return sales
def my_active_sale_details(seller_id): connector = Dao.get_connection() cursor = connector.cursor(dictionary=True) now = datetime.now() query = "SELECT id, seller_id, startdate, enddate, address_line_one, address_line_two, city, state, country, pincode, start_price FROM sale " \ "WHERE endstart > %s AND seller_id = %s" cursor.execute(query, (now, seller_id)) sales_from_database = cursor.fetchall() sales = {} for row in sales_from_database: sale = Sale(row["seller_id"], row["startdate"], row["enddate"].strftime('%m/%d/%Y'), row["address_line_one"], row["address_line_two"], row["city"], row["state"], row["country"], row["pincode"], row["start_price"]) sales[row['id']] = sale cursor.close() connector.close() ''' { 1 : salesObj1, 2 : salesObj2, 4 : saledObj3 } ''' return sales
def create_search_table(db_info, table_name): connector = mysql.connector.connect( auth_plugin='mysql_native_password', host = db_info["host"], user = db_info["user"], passwd = db_info["passwd"], db = db_info["db_name"], ) cursor = connector.cursor() sql = """ CREATE TABLE IF NOT EXISTS %s( id BIGINT PRIMARY KEY AUTO_INCREMENT, tweet_id BIGINT unique not null, datetime DATETIME, user_id BIGINT, user_name VARCHAR(50), text TEXT ) ; """ %(table_name) cursor.execute(sql) connector.commit() cursor.close() connector.close()
def handle(session_id, item_id, file_name): # session_ids are 16 characters long if (len(session_id) > 16): return '', status.HTTP_400_BAD_REQUEST connector = mysql.connector.connect( user=conf.user, database=conf.database, passwd=conf.passwd, host=conf.host, port=conf.port) cursor = connector.cursor() return_status = cursor.callproc('delete_item_image', args=[session_id, item_id, file_name, 0]) if(return_status[3] == 0): # all according to keikaku # (keikaku means plan) # now that the image has been deleted from the db that actually also confirmed that it was a legitimate request, # so we can delete the file with a good conscience remove(conf.web_root + '/' + conf.image_directory + '/' + item_id + '/' + file_name) connector.close() return '', status.HTTP_200_OK elif(return_status[3] == 1): # no image for that item for that vendor for that user found connector.close() return '', status.HTTP_404_NOT_FOUND
def handle(): connector = mysql.connector.connect(user=conf.user, database=conf.database, passwd=conf.passwd, host=conf.host, port=conf.port) answer = [] cursor = connector.cursor() cursor.callproc('get_manufacturers') result = next(cursor.stored_results()) for (manufacturer_id, manufacturer_name, manufacturer_description) in result: entry = {} entry['manufacturer_id'] = manufacturer_id entry['manufacturer_name'] = manufacturer_name entry['manufacturer_description'] = manufacturer_description answer.append(entry) connector.close() return json.dumps(answer), status.HTTP_200_OK
def LoadGuidFromDB(): try: serverConfig = gTableManager.getServerConfigListById(ServerId()) connConfig = {} connConfig['user'] = serverConfig.DBUser connConfig['password'] = serverConfig.DBPsw connConfig['database'] = serverConfig.DBName connConfig['host'] = serverConfig.DBIp connConfig['port'] = serverConfig.DBPort # 默认的链接编码为utf8,但是我们依然要明文指定为utf8 connConfig['charset'] = 'utf8' # 需要保证一点:数据库存储数据必须为utf8格式。客户端、服务器、数据库包括其中的链接必须是utf8 connector = mysql.connector.connect(**connConfig) cursor = connector.cursor(buffered=True) cursor.execute('select * from t_guid') resultCount = cursor.rowcount DB_TYPE = 0 DB_CARRY = 1 DB_SERIAL = 2 for i in range(resultCount): resultTuple = cursor.fetchone() print(resultTuple) type = resultTuple[DB_TYPE] carry = resultTuple[DB_CARRY] serial = resultTuple[DB_SERIAL] gGuidGenerator.append(GuidGenerator(type, carry, serial)) cursor.close() connector.close() except BaseException as err: ASSERT(False, 'loadGuidFromDB, ' + str(err))
def insert_into_twitter_search(db_info, search_query): connector = mysql.connector.connect(auth_plugin='mysql_native_password', host=db_info["host"], user=db_info["user"], passwd=db_info["passwd"], db=db_info["db_name"], charset="utf8mb4") cursor = connector.cursor() sql = """ INSERT INTO %s VALUES( NULL, '%s', '%s', '%s', '%s', '%s', '%s', '%s' ) ; """ % (local_db["table_name"], search_query["user_id"], search_query["user_name"], search_query["screen_name"], search_query["location"], search_query["description"], search_query["latest_tweet_text"], search_query["latest_tweet_created_at"]) cursor.execute(sql) connector.commit() cursor.close() connector.close()
def get(self): co = {} co["user"] = self.get_argument('user') co["password"] = self.get_argument('password') co["host"] = self.get_argument('host') co["db"] = self.get_argument('db') connector = mysql.connector.connect(user=co["user"], password=co["password"], host=co["host"], database=co["db"]) cursor = connector.cursor() try: cursor.execute("show tables") tables = cursor.fetchall() uuid = self.GenUUID() self.render("tables.html", co = co, tables = tables, uuid = uuid) except mysql.connector.Error as e: self.render("tables.html", co = co, message = "get tables error") # raise e finally: cursor.close() connector.close()
r, Vec = get_pagerank(NewMatrix, alpha=0, return_P=True) for i in range[0:len(r)]: print i,UseList[r[i]],Vec[[i]] #g.add_edge(IdDict[9462],IdDict[589960]) #g.add_edge(IdDict[295386],IdDict[21222]) """ """ pr=nx.pagerank(g,alpha=0.85) prn=nx.pagerank_numpy(g,alpha=0.85) prc=nx.pagerank_scipy(g,alpha=0.85) print pr[0:10] #namespace2のやつとかはlimkto しかなく、ネットワークには入っていないので除外してもよいと考えた sql = 'select cl_from from categorylinks where cl_to = "存命人物"' cursor.execute(sql) HumanIdList = cursor.fetchall() HumanIdlist = np.zeros([len(HumanIdList)]) k = 0 for j in HumanIdList: try: HumanIdlist[k] = IdDict[j[0]] k = k + 1 except: #人間辞書にないやつはしょぼいやつ、あるいは関係ないやつなので考えない。 print j continue #k = 151937 """ cursor.close() connector.close()