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 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_new_auth(): print("Getting a new auth code for the stream data") # Getting the characters location # Checking how hardcore we are on updating json_input = request.data.decode('utf-8') json_data = json.loads(json_input) # Authenticating our user auth = auth_character(json_data['character_id'], json_data['character_auth_code']) if auth == -1: return throw_json_error(400, "Invalid authentication code") ### Okay, we will now proceed to generate a new authentication token.... new_token = gen_random_string(8) ### Inserting into our database connector = init_mysql("db_cctv") cursor = connector.cursor() INSERT_CCTV_TOKEN = "INSERT INTO tb_cctv_token (cctv_token_code, cctv_init_character) VALUES (%s, %s)" cursor.execute(INSERT_CCTV_TOKEN, (new_token, json_data['character_id'])) connector.commit() return throw_json_success("Success", new_token)
def echo_all(message): order = message.text.split('#') room_number = order[1] name = order[2] telephone = order[3] id_number = order[4] cursor.execute( "INSERT INTO `pelanggan` (`id_pelanggan`, `nama_pelanggan`, `nomor_telepon`, `nomor_identitas`) VALUES (NULL, '" + name + "', '" + telephone + "', '" + id_number + "');") connector.commit() cursor.execute("SELECT pelanggan.id_pelanggan FROM `pelanggan` WHERE `nama_pelanggan` LIKE '%" + name + "%' ") data_customer = cursor.fetchone() data_customer_str = str(data_customer) data_customer_str = data_customer_str.replace('(', '') data_customer_str = data_customer_str.replace(')', '') data_customer_str = data_customer_str.replace(',', '') cursor.execute("SELECT kamar.id_kamar FROM `kamar` WHERE `nomor_kamar` = " + room_number) data_room = cursor.fetchone() data_room_str = str(data_room) data_room_str = data_room_str.replace('(', '') data_room_str = data_room_str.replace(')', '') data_room_str = data_room_str.replace(',', '') cursor.execute( "INSERT INTO `reservasi` (`id_reservasi`, `id_pelanggan`, `id_kamar`, `tgl_checkin`) VALUES (NULL, '" + data_customer_str.strip() + "', '" + data_room_str.strip() + "', CURRENT_DATE());") connector.commit() bot.reply_to(message, data_customer_str.strip())
def update_s(brand=None, model_no=None, parameter=None, update=None): try: if brand == None: brand = input('Enter Brand : ') model_no = input('Enter Model No : ') parameter = input('Enter Parameter : ') update = input('Enter Update : ') p_meter = (update, brand, model_no) query = f'UPDATE LAPTOP SET {parameter}' + '=%s WHERE BRAND=%s AND MODEL_NO=%s' cursor.execute(query, p_meter) connector.commit() print( f'Successfully Updated {cursor.rowcount} Row Updated : {parameter} Of {brand}-{model_no} To {update}' ) except mysql.connector.Error as error: print(f'Error : {error}')
def edit_user(user: UserModel): handled = False connector = SqlController().sql_connector cursor = connector.cursor() sql = "UPDATE user " \ "SET realname = %s, nickname = %s, gender = %s, location = %s, " \ "email = %s, tags = %s, selfdescription = %s " \ "WHERE userid = %s" val = (user.name, user.nickname, user.gender, user.location, user.email, user.tags, user.description, user.uid) try: cursor.execute(sql, val) connector.commit() if cursor.rowcount == 0: handled = True return Errors.MISSING.name else: handled = True return user.uid except mysql.connector.errors.IntegrityError as err: print(err.msg) if not handled: handled = True return Errors.DUPLICATE.name finally: connector.rollback() if not handled: return Errors.FAILURE.name
def UpdateClientAttributes(connector, table, conditionCategory, condition): c = connector.cursor() data = (table, conditionCategory, condition) if conditionCategory in ('ClientName', 'Email'): # force ID lookup select_query = """SELECT Client_ID FROM %s WHERE %s LIKE '%s'""" % ( data[0], data[1], "%" + str(data[2]) + "%") c.execute(select_query, ) result = c.fetchall() for i in result: for j in i: if j >= 1: condition = j conditionCategory = 'Client_ID' data = (table, conditionCategory, condition) select_query = """SELECT * FROM %s WHERE %s = %s""" % (data[0], data[1], str(data[2])) c.execute(select_query, ) printResultTable(c) userChoice = getWholeNumberChoice(update_client_options) while userChoice != 0: update_value = '' column = '' if userChoice == 1: # name update_value = input(clientInName) column = 'ClientName' elif userChoice == 2: # address update_value = input(addressInMessage) column = 'Address' elif userChoice == 3: # city update_value = input(cityInMessage) column = 'City' elif userChoice == 4: # state update_value = input(stateInMessage) if len(update_value) != 2 or re.search('[0-9]', update_value): print('Error: State Values are accepted in format: \'CA\'') else: column = 'State' elif userChoice == 5: # zip update_value = input(zipInMessage) if len(update_value) != 5 or re.search('[a-zA-Z]', update_value): print("Error: zip code is 5 integers ex: 55555...\n") else: column = 'Zip' elif userChoice == 6: # email update_value = input(emailInMessage) column = 'Email' elif userChoice == 7: # phone update_value = input(phoneInMessage) column = 'Phone' str_column = str(column) if column != '': query = """UPDATE %s SET %s = '%s' WHERE (%s = '%s')""" % ( table, str_column, update_value, conditionCategory, condition) c.execute(query, ) connector.commit() c.execute(select_query, ) printResultTable(c) userChoice = getWholeNumberChoice(update_client_options) return 0
def add_search(): print("Adding a new search entry") # Getting the sig info json_input = request.data json_data = json.loads(json_input.decode('utf-8')) ### Authenticating the player # Authenticating our user auth = auth_character(json_data['character_id'], json_data['character_auth_code']) if auth == -1: return throw_json_error(400, "Invalid authentication code") # Authenticating our user auth = auth_character(json_data['character_id'], json_data['character_auth_code']) if auth == -1: return throw_json_error(400, "Invalid authentication code") connector = init_mysql("db_map") cursor = connector.cursor() # Adding a new sig ADD_NEW_SEARCH = "INSERT INTO tb_search (search_name, search_character) VALUES (%s, %s)" cursor.execute(ADD_NEW_SEARCH, (json_data['search_name'], json_data['character_id'])) connector.commit() throw_json_success("Success", {})
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 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 add(): if request.method == "POST": # dummy data # lat = [(49.060329), (50.060329)] # lon = [(-122.462227), (-123.462227)] # title = [("title0"), ("title1")] # description = [("desc0"), ("desc1")] latitude = request.form.get("inputLatitude") longitude = request.form.get("inputLongitude") title = request.form.get("inputTitle") description = request.form.get("inputDescription") locType = request.form.get("inputType") db.execute( 'INSERT INTO locations (latitude, longitude, title, description, locType) VALUES (?, ?, ?, ?, ?)', (latitude, longitude, title, description, locType)) connector.commit() # for lt,ln,nm,ds in zip(latitude,longitude,title,description): # db.execute('INSERT INTO locations (latitude, longitude, title, description) VALUES (?, ?, ?, ?)', (lt, ln, nm, ds)) # # db.execute('INSERT INTO locations (lat, long) VALUES (?, ?)', (lat, lon)) return redirect("/map") else: return render_template("add.html")
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_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_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 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 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 add_user(user: UserModel): connector = SqlController().sql_connector cursor = connector.cursor() handled = False sql = "INSERT INTO user " \ "(realname, nickname, gender, location, email, tags, selfdescription) " \ "VALUES " \ "(%s, %s, %s, %s, %s, %s,%s)" val = (user.name, user.nickname, user.gender, user.location, user.email, user.tags, user.description) try: cursor.execute(sql, val) connector.commit() handled = True return Errors.SUCCESS.name except mysql.connector.errors.IntegrityError as err: print(err.msg) if not handled: handled = True return Errors.DUPLICATE.name finally: connector.rollback() if not handled: return Errors.FAILURE.name
def save(params): # Get database connection database = Database() connector = database.connect() cursor = database.cursor() # Build query to insert data query = ( "INSERT INTO posts " "(origin_id, origin_url, title, description ,image, crawl_status, created_at, updated_at) " "VALUES (%(origin_id)s, %(origin_url)s, %(title)s, %(description)s, %(image)s, %(crawl_status)s, %(created_at)s, %(updated_at)s)" ) # Total queries count = 0 # Insert new posts try: result = cursor.execute(query, params) connector.commit() # Increase total queries count += cursor.rowcount except mysql.connector.IntegrityError as err: print("PostModel.save: {}".format(err)) return False return count
def executeS(sql: str = None, args: dict = None): ExceptLog = None retVal = None connector = None cursor = None try: if sql is None: raise Exception('Invalid Sql : None type') connector, cursor = connect() if args is None: cursor.execute(sql) else: cursor.execute(sql, args) connector.commit() retVal = True except Exception as Ex: if ExceptLog is None: ExceptLog = osLogger.cOSLogger(_pPrefix='Exception', _pLevel='ERROR') ExceptLog.writeLog('[osDB:executeS] ' + str(Ex)) ExceptLog.writeLog('SQL : \n' + sql) ExceptLog.writeLog('Variable : ' | str(args)) if connector is not None: connector.rollback() retVal = False finally: close(connector, cursor) return retVal
def pop_must_dock(): get_ss_id = 'SELECT SS_ID FROM spaceship' cursor.execute(get_ss_id) ssid_list = list(cursor.fetchall()) ssid_length = len(ssid_list) get_empty_docks = 'SELECT Dock_Number FROM landing_dock WHERE isAvailable = 1 LIMIT ' + str( ssid_length) cursor.execute(get_empty_docks) dock_number_list = list(cursor.fetchall()) add_must_dock = ('INSERT INTO must_dock' '(SS_ID, Dock_Number) VALUES (%s, %s)') for i in range(0, ssid_length): data_must_dock = ('%s' % ssid_list[i], '%s' % dock_number_list[i]) # print(data_must_dock) do_query(add_must_dock, data_must_dock) # update landing_dock isAvailable to 0 get_dock_num = 'SELECT Dock_Number FROM must_dock' cursor.execute(get_dock_num) dock_list = list(cursor.fetchall()) length = len(dock_list) for i in range(0, length): update_landing_dock = 'UPDATE landing_dock SET isAvailable = 0 WHERE Dock_Number = ' + '%s' % dock_list[ i] cursor.execute(update_landing_dock) connector.commit() # commit changes
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 g(ips, tag, url): # if tag = "https" sql = 'drop table if exists val{}'.format(tag) cur.execute(sql) sql = 'create table val{} (id int(11) auto_increment primary key,ip char(88) not null)'.format( tag) cur.execute(sql) url = url[tag] for i in range(len(ips)): proxie = {tag: ips[i][1]} try: res = requests.get(url, proxies=proxie, timeout=2) print(res.status_code) print(ips[i]) print(ips[i][1]) valideip[tag].add(ips[i][1]) sql = 'insert into val{} (ip) values ("{}")'.format(tag, ips[i][1]) print(sql) cur.execute(sql) db.commit() output.write("\r{:<4.2f}% completed".format(i / len(ips) * 100)) # break except BaseException as e: output.write( "\r{:<4.2f}% completed but something is wrong!".format( i / len(ips) * 100)) return valideip
def delete(): connector = mysql.connector.connect(host='127.0.0.1', port=3306, user='******', passwd='root', database='comma', auth_plugin='mysql_native_password') mycursor = connector.cursor() sql = 'delete from student where name="喵喵"' mycursor.execute(sql) connector.commit() print('删除了', mycursor.rowcount, '条数据')
def update(): connector = mysql.connector.connect(host='127.0.0.1', port=3306, user='******', passwd='root', database='comma', auth_plugin='mysql_native_password') mycursor = connector.cursor() sql = 'update student set name="渣渣" where name="黄月英"' mycursor.execute(sql) connector.commit() print('更新了', mycursor.rowcount, '条数据')
def insert_deck(connector, data): cursor = connector.cursor() insert_query = ("INSERT IGNORE INTO decks " "(id, name)" "VALUES (%(id)s, %(name)s)") cursor.execute(insert_query, data) connector.commit() cursor.close()
def insertProduct(path, uploader): con = connection() cursor = con.cursor() cur_time = dt.now().strftime('%s') sql = "INSERT INTO katalog (path, user_email, upload_date) VALUES (%s, %s, %s)" cursor.execute(sql, (path, uploader, cur_time)) con.commit() cursor.close() return True
def add_laptop(brand, model_no, processor=None, graphic_card=None, os=None, ram=None, display=None, storage=None, camera=None, battery=None, keyboard=None, other_inputs=None, speakers=None, ports=None, wifi=None, bluetooth=None, weight=None, warranty=None, year_of_release=None, manufacture_in_country=None, stocks=None, price=None, others=None, productcode=None): try: # converting all parameters into upper case parameters = [ productcode, brand, model_no, processor, graphic_card, os, ram, display, storage, camera, battery, keyboard, other_inputs, speakers, ports, wifi, bluetooth, weight, warranty, year_of_release, manufacture_in_country, stocks, price, others ] for val in range(len(parameters)): if f'{parameters[val]}'.isalnum() == False: parameters[val] = parameters[val].upper() parameters = tuple(parameters) #insertion query = ( 'INSERT INTO LAPTOP 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)' ) cursor.execute(query, parameters) connector.commit() print( f'\nSuccessfully Added! \'{color(6)}{brand}-{model_no}{color()}\'\n' ) except mysql.connector.Error as error: print(f'\nUnable To Add New Product : {error}\n')
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 add_data(db, connector): name = input("Enter your first and last name: ") age = int(input("Enter your age: ")) dob = input("Enter your date of birth (mmm-dd-yyyy): ") height = input("Enter your height (in inches.): ") pets = int(input("Enter the amount of pets you have: ")) db.execute("""INSERT INTO `%s` VALUES ('%s',%d,'%s','%s',%d);""" % (table, name, age, dob, height, pets)) connector.commit()
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 insert_card(connector, data): cursor = connector.cursor() insert_query = ( "INSERT IGNORE INTO cards " "(id, card_title, house, card_type, front_image, card_text, traits, amber, power, armor, rarity, flavor_text, card_number, expansion, is_maverick)" "VALUES (%(id)s, %(card_title)s, %(house)s, %(card_type)s, %(front_image)s, %(card_text)s, %(traits)s, %(amber)s, %(power)s, %(armor)s, %(rarity)s, %(flavor_text)s, %(card_number)s, %(expansion)s, %(is_maverick)s)" ) cursor.execute(insert_query, data) connector.commit() cursor.close()
def withdraw_sale(sale_id): connector = Dao.get_connection() cursor = connector.cursor() query = ("DELETE FROM sale WHERE id = %s") cursor.execute(query, (sale_id, )) connector.commit() cursor.close() connector.close()
bodyText = bodyText.replace("'","''") #title = title.replace('"','""') #title = title.replace("'","''") except: continue sql = "INSERT INTO News (NewsID, Timestamp, author, author_link, location, title,bodyText) VALUES("#,bodyText) VALUES(" sql += (str(m) + ",") sql += ('"' + timestamp + '"'+ ",") sql += ('"' + author + '"' + ",") sql += ('"' + author_link + '"' + ",") sql += ('"' + location + '"' + ",") sql += ('"' + title + '"') sql += ("," + '"' + bodyText + '"') sql += ') ;' j += 1 print sql print m cursor.execute(sql) """ sql = "CREATE TABLE News (Timestamp VARCHAR(32)," sql += "author VARCHAR(32) ,author_link longtext ,location longtext ,title VARCHAR(128) ," sql += "bodyText longtext) ENGINE=InnoDB DEFAULT CHARSET=utf8;" cursor.execute(sql) """ for day in ("05282015", "05292015", "05302015", "05312015", "06012015", "06022015","06032015"): SelectSportsnews(day) connector.commit() cursor.close() connector.close()