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 showUser(userName): connector = mysql.connector.connect( user='******', password=os.environ['PASSWORD'], host='localhost', database='debugger') cursor = connector.cursor() cursor.execute("select * from test where name = '" +userName + "'") #print(cursor.fetchall()) users = cursor.fetchall() if len(users) == 0: print("row is null") sys.stdout.write("Do you input %s or not?(Y/N)" % userName) flag = input() if flag == 'Y': cursor.execute("insert into test(name) values('" +userName + "')") print("Input a %s" % userName) else: for row in users: print("ID:" + str(row[0]) + " NAME:" + row[1]) connector.commit() cursor.close connector.close
def insert(connector,title,link,detail,updated_at): cursor = connector.cursor() sql = "insert into article (title,link,detail,updated_at) values ('" \ + title + "','" + link + "','" + detail + "','" + updated_at + "')" try: cursor.execute(sql) connector.commit() except (mysql.connector.errors.IntegrityError): print("WARNING. dupulicate error") cursor.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()
def get_ip(self) -> list: '''Возвращает список словарей вида [{ip: 0.0.0.0},{{ip: 0.0.0.0},...]''' connector = mysql.connector.connect(host=self.host, user=self.user, password=self.password, database=self.database) cursor = connector.cursor() querry = 'SELECT `adress1`,`adress2`,`adress3`,`adress4` FROM ip' cursor.execute(querry) ip_list = list() for (adress1, adress2, adress3, adress4) in cursor: ip_list.append({ 'ip': '.'.join( [str(adress1), str(adress2), str(adress3), str(adress4)]) }) connector.close() return ip_list
def set_country_from_web(self, ip_country): connector = mysql.connector.connect(host=self.host, user=self.user, password=self.password, database=self.database) cursor = connector.cursor() for elem in ip_country: if 'country' in elem: querry = 'UPDATE `ip` SET `country`=\'{}\', `country_code`=\'{}\' ' \ 'WHERE `adress1`=\'{}\' AND `adress2`=\'{}\' AND `adress3`=\'{}\' AND `adress4`=\'{}\'' \ .format(str(elem.get('country')), str(elem.get('countryCode')), str(elem.get('query').split('.')[0]), str(elem.get('query').split('.')[1]), str(elem.get('query').split('.')[2]), str(elem.get('query').split('.')[3])) else: querry = 'UPDATE `ip` SET `country`=\'undetermined\', `country_code`=\'undetermined\' ' \ 'WHERE `adress1`=\'{}\' AND `adress2`=\'{}\' AND `adress3`=\'{}\' AND `adress4`=\'{}\'' \ .format(str(elem.get('query').split('.')[0]), str(elem.get('query').split('.')[1]), str(elem.get('query').split('.')[2]), str(elem.get('query').split('.')[3])) cursor.execute(querry) connector.commit() connector.close()
def select_url(self, id): try: connector = self.connect_mysql() cursor = connector.cursor() query = (" SELECT full_url FROM Url_Shortening where id = %(id)s ") cursor.execute(query, {'id': id}) row = cursor.fetchone() if row: self.url = row[0] else: self.url = row except Exception as e: print(e) return self.createDataError("ERROR TO GET URL SHORTENING", "", "004") finally: cursor.close() connector.close() return self.url
def select_key(self): try: connector = self.connect_mysql() cursor = connector.cursor() query = (" UPDATE Seq_key SET id=LAST_INSERT_ID(id+1) ") cursor.execute(query) row = cursor.lastrowid self.key = row connector.commit() except Exception as e: return self.createDataError("ERROR TO GET NEW KEY", "", "005") finally: cursor.close() connector.close() return self.key
def RecordExistsDate(connector, table, conditionCategory, condition): cursor = connector.cursor() data = (table, conditionCategory, condition) start_date = data[2].strftime('%Y-%m-%d %H:%M:%S') end_date = (data[2] + timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S') # SELECT * FROM Job WHERE (Last_active >= '2020-03-23 00:00:00') AND (Last_active <= '2020-03-24 00:00:00'); query = """SELECT * FROM %s WHERE (%s >= '%s') AND (%s <= '%s')""" % ( data[0], data[1], start_date, data[1], end_date) cursor.execute(query, ) row_count = cursor.rowcount results = cursor.fetchall( ) # gets the number of rows affected by the command executed if not results: # checks "truth-iness" of the returned list - false if empty print('Record does not exist\n') return False elif row_count > 1: print("{} similar rows...\n".format(row_count)) print( "Multiple matching records please use another method to update...\n" ) return False return True
def RecordExistsTwoCondition(connector, table, conditionCategory, condition, conditionCategory_Two, condition_Two): cursor = connector.cursor() data = (table, conditionCategory, condition, conditionCategory_Two, condition_Two) query = """SELECT * FROM %s WHERE %s = '%s' AND %s = '%s'""" % ( data[0], data[1], data[2], data[3], data[4]) cursor.execute(query, ) results = cursor.fetchall( ) # clears cursor results to allow for next query if needed # gets the number of rows affected by the command executed row_count = cursor.rowcount if not results: print('record does not exist\n') return False elif row_count > 1: print("{} similar rows...".format(row_count)) print( "Multiple matching records please use another method to update...\n" ) return False return True
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_tags') result = next(cursor.stored_results()) for (tag_id, tag_name) in result: answer.append(tag_name) connector.close() return json.dumps(answer), status.HTTP_200_OK
def my_bid_details(bidder_id): connector = Dao.get_connection() cursor = connector.cursor(dictionary=True) query = ( "SELECT bidder_id, MAX(bid_price) AS recent_bid_price, seller_id, start_price, startdate, " "enddate, address_line_one, address_line_two, city, state, country, pincode FROM bid INNER JOIN sale " "ON sale_id = sale.id " "WHERE bidder_id=%s GROUP BY sale_id") cursor.execute(query, (bidder_id, )) #print cursor.statement bids = cursor.fetchall() sales_list_of_dict = [] for bid in bids: sale = Sale(bid["seller_id"], bid["startdate"], bid["enddate"].strftime('%m/%d/%Y'), bid["address_line_one"], bid["address_line_two"], bid["city"], bid["state"], bid["country"], bid["pincode"], bid["start_price"]) bid_sale_info_dict = { "sale": sale, "recent_bid_price": bid["recent_bid_price"] } sales_list_of_dict.append(bid_sale_info_dict) cursor.close() connector.close() ''' [ { "sale" : Saleobjcect1, "recent_bid_price" :500 }, { "sale" : Saleobjcect2, "recent_bid_price" :120000 }, { "sale" : Saleobjcect3, "recent_bid_price" :2300 }, ] ''' return sales_list_of_dict
def insert(): connector = mysql.connector.connect(host='localhost', user='******', passwd='sun123456', database='comma', auth_plugin='mysql_native_password') # print(connector) mycursor = connector.cursor() # 编写SQL语句 sql = 'insert into student (name,Python,sex) values (%s,%s,%s)' ############# 单条数据插入 ###################### # value = ('二豆', 89, 1) # 单行数据插入 # 执行SQL语句 # mycursor.execute(sql, value) # 单行数据执行 ############ 批量数据插入 ################## values = [('狗蛋', 85, '女'), ('二蛋', 58, '女'), ('三傻', 79, '男')] mycursor.executemany(sql, values) # 提交 connector.commit() print('插入了', mycursor.rowcount, '条数据')
def set_account_group(): # Getting the request info json_input = request.data json_data = json.loads(json_input.decode('utf-8')) ### Authenticating the player # Authenticating our user auth = auth_character_full(json_data['character_id'], json_data['character_auth_code'], "admin") if auth == -1: return throw_json_error(400, "Invalid authentication code") # Authenticated connector = init_mysql("db_character") cursor = connector.cursor(dictionary=True) set_character_group = "UPDATE tb_character SET character_type = %s WHERE character_id = %s" cursor.execute( set_character_group, (json_data['character_type'], json_data['target_character'])) connector.commit()
def create_database(self): connector = self.connector() cursor = connector.cursor() try: connector.database = environ.get('MYSQL_DB') except mysql.connector.Error as err: if err.errno == errorcode.ER_BAD_DB_ERROR: try: cursor.execute( "CREATE DATABASE {} DEFAULT CHARACTER SET 'utf8'". format(environ.get('MYSQL_DB'))) except mysql.connector.Error as err: logger.info(f"Failed creating database: {err}") exit(1) connector.database = environ.get('MYSQL_DB') else: logger.info(err) exit(1) cursor.close() connector.close()
def execute_and_fetch(*args, commit=False, connector=None): """ Execute a serie of queries to known cursor ===================================================== >>> from zilean import execute_sql >>> from zilean import mysql_local_connection >>> crs = m() >>> execute_sql("SHOW DATABASE", cursor=crs) [('information_schema',), ('mysql',), ('performance_schema',), ('sys',), ('zileansystem',)] ===================================================== """ result = [] try: cursor = connector.cursor() except: raise BadConnector(connector) for query in list(args): cursor.execute(query) for e in cursor: result.append(e) if commit: connector.commit() return result
def handle(): 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() manufacturer_name = data['manufacturer_name'] manufacturer_description = data['manufacturer_description'] return_status = cursor.callproc( 'add_manufacturer', args=[manufacturer_name, manufacturer_description, 0]) answer = {} answer['manufacturer_id'] = return_status[2] connector.close() return json.dumps(answer), status.HTTP_200_OK
def see_event_details(): if request.method == "POST": event_creater = request.form['creater'] daytime = request.form['daytime'] 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 player FROM events_master WHERE creater = "' + event_creater + '"' cursor.execute(query) group = cursor.fetchall() players = [] for player in group: players.append(player[0]) event_players = ','.join(players) return event_players
def get_all_valid_sales(index): connector = Dao.get_connection() cursor = connector.cursor(dictionary=True) now = datetime.now() offset = (index - 1) * SALE_COUNT query = "SELECT id, seller_id, startdate, enddate, address_line_one, address_line_two, city, state, country, pincode, start_price FROM sale WHERE enddate > %s AND startdate < %s ORDER BY startdate LIMIT %s, %s" cursor.execute(query, (now, now, offset, SALE_COUNT)) #print "query executed is: ", cursor.statement, "\n\n" sales = {} rows = cursor.fetchall() for row in rows: 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 return sales
def get_text(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 = """ SELECT TEXT FROM %s; """ % (table_name) cursor.execute(sql) text = cursor.fetchall() # 出力 joined_text = '' tweets = [] for i in text: joined_text += i[0] tweets.append(i[0]) cursor.close() connector.close() return tweets
def get_max_bid_price(sale_id): # select max(bid_price) as max_price from bid where sale_id=3; connector = Dao.get_connection() cursor = connector.cursor() print sale_id query = "select max(bid_price) as max_price from bid where sale_id = %s" cursor.execute(query, (sale_id, )) # print "query executed is: ", cursor.statement max_price = None row = cursor.fetchone() if row: max_price = row[0] print "Max price for sale id %s is %s" % (sale_id, max_price) else: print "No max price for the sale" cursor.close() connector.close() return max_price
def insertSchoolTodb(school): connector = myDatabaseConnector() mycursor = connector.cursor() #insert school data to db db_querry = "insert into schools(schoolName,schoolAddress,schoolCode,student_id) values (%s,%s,%s,%s);" values = (school.schoolname, school.schoolAddress, school.schoolCode, school.studentID) mycursor.execute(db_querry, values) connector.commit() print(mycursor.rowcount, "record inserted.") #get inserted school code tdb_querry = "select * from schools where schoolCode=%s;" sch_idvalue = (school.schoolCode, ) mycursor.execute(tdb_querry, sch_idvalue) #fetch inserted school code in the database insertedschool = mycursor.fetchone() print(insertedschool)
def get_user_id(email, password): connector = Dao.get_connection() cursor = connector.cursor() print email query = ("SELECT id FROM user " " WHERE email = %s AND password = %s") hashed_password = get_hashed_password(password) cursor.execute(query, (email, hashed_password)) # print "query executed is: ", cursor.statement user_id = None row = cursor.fetchone() if row: user_id = row[0] print "Found user and password with id=", user_id else: print "Found no user and password match" cursor.close() connector.close() return user_id
def login(): if request.method == "POST": username = request.form['username'] connector = mysql.connector.connect(host='us-cdbr-east-02.cleardb.com', user='******', password='******', database='heroku_26cfe5af0cd58f4') if connector.is_connected(): cursor = connector.cursor() query = 'SELECT invitor, team FROM notifications_master WHERE invited = "' + username + '"' cursor.execute(query) your_notifications = cursor.fetchall() cursor.close() connector.close() notifications = [ str(x[0] + '-' + x[1] + ' -- ') for x in your_notifications ] notifications = ''.join(notifications) print(notifications) return notifications
def register(): if request.method == 'POST': groupid = request.form['groupid'] playerid = request.form['playerid'] creator = playerid playtime = request.form['playerid'] #date = request.form['datetime'] date = datetime.datetime.now() #date = datetime.datetime(date) eventname = request.form['eventname'] maxplayers = request.form['maxplayers'] groupid = request.form['groupid'] eventid = randint(10000,99999) connector = mysql.connector.connect(host='localhost',user='******',database='flexplay') cursor = connector.cursor() query = 'SELECT eventid FROM event_master' cursor.execute(query) all_event_id = cursor.fetchall() while eventid in all_event_id: eventid = randint(10000,99999) query = 'INSERT INTO event_master (eventid, date, playtime, maxplayers, creator, eventname, groupid) VALUES (%s, %s, %s, %s, %s, %s, %s)' values = eventid, date, playtime, maxplayers, creator, eventname, groupid cursor.execute(query, values) connector.commit() query = 'INSERT INTO event_players (playerid, eventid) VALUES (%s,%s)' values = playerid, eventid cursor.execute(query, values) connector.commit() cursor.close() connector.close() return 'Created event' return 'Couldnt create event. Something went wrong'
def select_user(db_info, id): 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(buffered=True) sql = """ SELECT screen_name FROM %s WHERE id = %s ; """ % (db_info["username_table"], id) print(sql) cursor.execute(sql) # print(cursor.fetchall())#190315 なぜかここのprintを出力しないと,エラーになる. Us = cursor.fetchall() print(len(Us)) print(Us[0][0]) if len(Us) == 0: # print() u = 0 # 仮に else: # print(cursor.fetchall()[0])#[0] is None) # print(cursor.fetchall()) # u = cursor.fetchall()[0][0] u = Us[0][0] print(u) connector.commit() cursor.close() connector.close() return u
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 len(groups) != 0: player_groups = {} for group in groups: group = group[0] query = 'SELECT groupname FROM group_master WHERE groupid = "' + group + '"' cursor.execute(query) group_name = cursor.fetchone() try: group_name = ''.join(group_name) except: None player_groups[group] = {'name': group_name} else: return 'player not associated with any group' cursor.close() connector.close() return jsonify({'groups': player_groups})
def f3(request): ''' 从数据库里取数据 将数据写成html格式 并作替换(模板的渲染) ''' 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.html', 'r', encoding='utf-8', errors='ignore') response = f.read() f.close() movie_html_list = [] #movie_html ='' for movie in movie_list: name = '<th>' + movie[0] + '</th>' score = '<th>' + str(movie[1]) + '</th>' date = '<th>' + movie[2] + '</th>' # movie_html =movie_html +'<tr>'+name+score+date+'</tr>' movie_html = '<tr>' + name + score + date + '</tr>' movie_html_list.append(movie_html) # print(movie_html) content = ''.join(movie_html_list) ''' 模板的渲染(模板加数据) ''' response = response.replace('@@content@@', content) return (response)
def handle(session_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() name = data['name'] description = data['description'] return_status = cursor.callproc('add_vendor', args=[session_id, name, description, 0, 0]) if (return_status[4] == 0): # succ ess vendor_id = return_status[3] connector.close() return '', status.HTTP_200_OK elif (return_status[4] == 1): # user not found connector.close() return '', status.HTTP_401_UNAUTHORIZED else: # yikes connector.close() return '', status.HTTP_500_INTERNAL_SERVER_ERROR
def handle(amount): # amount should be > 1 if (amount < 1): 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) answer = [] cursor = connector.cursor() cursor.callproc('get_random_items', args=[amount]) result = next(cursor.stored_results()) for line in result: answer.append(line[0]) cursor.close() return json.dumps(answer), status.HTTP_200_OK
def makehtml(): cursor = connector.cursor() cursor.execute(query) html = base for session in cursor: ip = str(session[0]) login = (session[1]).encode('ascii', 'ignore').decode('ascii') password = (session[2]).encode('ascii', 'ignore').decode('ascii') date = str(session[3]) if login == 'root' and password == '1234': info = "<tr><td>" + ip + \ "</td><td><font color='red'>" + login + \ "</font></td><td><font color='red'>" + password + \ "</font></td><td>" + date + "</td></tr>\n" else: info = "<tr><td>" + ip + \ "</td><td>" + login + \ "</td><td>" + password + \ "</td><td>" + date + "</td></tr>\n" html = html + info html = html + "</html>" cursor.close() return html
def handle(session_id, item_id, amount): # no adding negative amounts to your cart if (int(amount) < 0): return 'no.', status.HTTP_403_FORBIDDEN # 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() result = cursor.callproc('add_item_to_cart', args=[session_id, item_id, amount, 0]) if (result[3] == 0): # 0 is a success connector.close() return '', status.HTTP_200_OK elif (result[3] == 1): # 1 means the session id could not be found connector.close() return '', status.HTTP_401_UNAUTHORIZED elif (result[3] == 2): # 2 means the item_id could not be found connector.close() return '', status.HTTP_404_NOT_FOUND else: # fatal system failure connector.close() return '', status.HTTP_500_INTERNAL_SERVER_ERROR
def insertStudentTodb(student): connector = myDatabaseConnector() mycursor = connector.cursor() #insert student data to db db_querry = "insert into students(name,regNumber) values (%s,%s);" values = (student.name, student.regNumber) mycursor.execute(db_querry, values) connector.commit() print(mycursor.rowcount, "record inserted.") #get inserted student id tdb_querry = "select * from students where regNumber=%s;" sch_idvalue = (student.regNumber, ) mycursor.execute(tdb_querry, sch_idvalue) #fetch inserted student id in the database inserted_id = mycursor.fetchone() print(inserted_id) studentID = inserted_id[2] return studentID
def add_user(user: UserModel): connector = SqlController().sql_connector cursor = connector.cursor() handled = False sql = "INSERT INTO user " \ "(realname, nickname, gender, location, email, tags, selfdescription, googleid, image) " \ "VALUES " \ "(%s, %s, %s, %s, %s, %s, %s, %s, %s)" val = (user.name, user.nickname, user.gender, user.location, user.email, user.tags, user.description, user.google_id, user.image) try: cursor.execute(sql, val) connector.commit() handled = True return Errors.SUCCESS.name except mysql.connector.errors.IntegrityError as err: if not handled: handled = True return Errors.DUPLICATE.name finally: connector.rollback() if not handled: return Errors.FAILURE.name
Returns: array of index in ascending order of PageRank """ n = len(M) M += np.ones([n, n]) * alpha / n la, v = scipy.sparse.linalg.eigs(M, k=1) P = v[:, 0] P /= P.sum() if return_P: return np.argsort(P)[-1::-1], P else: return np.argsort(P)[-1::-1] #CREATE TABLE IdLink (Number_to INT,from_id INT, to_id INT, Number_from INT)ENGINE=InnoDB DEFAULT CHARSET=utf8 ; connector = MySQLdb.connect(host="localhost", db="wiki", user="******",passwd="", charset="utf8") cursor = connector.cursor() sql = u"SELECT page_id FROM page where page_namespace = 0 AND page_namespace = 0 ORDER BY page_counter Desc;" #page_etsuransuu 大きい順 cursor.execute(sql) Id_from = cursor.fetchall() maxId = len(Id_from) IdDict = {} NumberDict = {} CounterDict = {} #maxId = 13617 #有向グラフのインスタンスを生成 #g = nx.DiGraph() #for i in range(0,maxId): #g.add_node(i) Matrix = np.zeros([maxId,maxId])