Example #1
1
    def __insert_tweet(self, tweet):
        """ Insert tweet into db.
            
            Args:
            tweet: Tweet object containing parsed tweet
        """

        try:
            sql = "INSERT INTO tweets VALUES" "(%d, '%s', '%s', %d, %d, %d, '%s', %d, %d)" % (
                tweet["tweet"]["tweet_id"],
                MySQLdb.escape_string(tweet["tweet"]["tweet_text"].encode("utf-8").strip()),
                tweet["tweet"]["created_at"].strftime("%Y-%m-%d %H:%M:%S"),
                tweet["tweet"]["geo_lat"],
                tweet["tweet"]["geo_long"],
                tweet["user"]["user_id"],
                MySQLdb.escape_string(tweet["tweet"]["tweet_url"].encode("utf-8").strip()),
                tweet["tweet"]["retweet_count"],
                tweet["tweet"]["original_tweet_id"],
            )

            self.cursor.execute(sql)

        except Exception, e:
            if "or read-only" not in str(e) and "1062" not in str(e):
                self.print_err("__insert_tweet", str(e))
Example #2
1
def activate_billing_account(userid, account):
    stmt = (
        "INSERT IGNORE INTO billing_account \
                SET userid = %d, money = %d, income = %d, create_time = NOW()"
        % (userid, account.money, account.money)
    )
    logger.debug(stmt)
    conn.ping(True)
    conn.autocommit(False)
    cur = conn.cursor()
    n = cur.execute(stmt)
    if n == 0:
        stmt = "UPDATE billing_account SET money = money + %d, income = income + %d WHERE userid = %d" % (
            account.money,
            account.money,
            userid,
        )
        logger.debug(stmt)
        cur.execute(stmt)
    stmt = "UPDATE anonymous_account SET flag = 1 WHERE device_id = '%s'" % MySQLdb.escape_string(account.device_id)
    logger.debug(stmt)
    cur.execute(stmt)
    stmt = "UPDATE billing_log SET userid = %d WHERE device_id = '%s'" % (
        userid,
        MySQLdb.escape_string(account.device_id),
    )
    logger.debug(stmt)
    cur.execute(stmt)
    conn.commit()
Example #3
1
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 #4
1
def get_group_name_from_plugin_svnrepo_path(svnrepo):
    path_elements = string.split(svnrepo, "/")
    repository_name = MySQLdb.escape_string(path_elements[len(path_elements) - 1])
    group_id = MySQLdb.escape_string(path_elements[len(path_elements) - 2])

    cursor = include.dbh.cursor(cursorclass=MySQLdb.cursors.DictCursor)

    query = 'SHOW TABLES LIKE "plugin_svn_repositories"'
    res = cursor.execute(query)

    if res > 0:
        query = (
            'SELECT g.unix_group_name FROM plugin_svn_repositories r JOIN groups g ON (g.group_id = r.project_id) WHERE project_id = "'
            + str(group_id)
            + '" AND name = "'
            + str(repository_name)
            + '"'
        )
        res = cursor.execute(query)
        row = cursor.fetchone()
        cursor.close()

        if cursor.rowcount == 1:
            return row["unix_group_name"]

    return False
def LogTrace(iso, host, mti, result):

    d = datetime.now()
    hex_dump = dumphex(iso.getNetworkISO())
    iso_dump = iso.dumpFields()

    if result != "":
        trasaction_result = ASResponseCodes.GetISOResponseText(result)
    else:
        trasaction_result = ""

    transaction_type = Tran_Type.GetMessagesescription(mti)

    sql = """ INSERT INTO switch_office.host_trace_log(
                        created,
                        host_data,
                        iso,
                        binary_data,
                        trasaction_result,
                        transaction_type
                        )

            VALUES ("%s", "%s", "%s", "%s", "%s", "%s")
          """ % (
        d,
        host,
        MySQLdb.escape_string(iso_dump),
        MySQLdb.escape_string(hex_dump),
        trasaction_result,
        transaction_type,
    )
    return sql
Example #6
1
def saveLog(logsObject, connection):
    sqlLog = (
        "INSERT INTO CommImportLog(log_value, rows_imported, rows_failed, rows_updated, created_at)"
        " VALUES ('SF API Import via Temp Json "
        + logsObject["tableName"]
        + "',"
        + str(logsObject["success"])
        + ","
        + str(logsObject["failed"])
        + ","
        + str(logsObject["updated"])
        + ",NOW())"
    )
    execute_sql(sqlLog, connection)
    cursor = connection.cursor()
    for id in logsObject["failedId"]:
        qCheckId = "select FailedId from CommImportFailed where FailedId = '" + id + "' "
        cursor.execute(qCheckId)
        currentRow = cursor.fetchone()
        if currentRow == None:
            sqlFailed = (
                "INSERT INTO CommImportFailed (`FailedTableName`, `FailedId`, `Action`, `Fixed`, `CreatedDate`, `LastModifiedDate`) VALUES ("
                + "'"
                + MySQLdb.escape_string(logsObject["tableName"])
                + "','"
                + MySQLdb.escape_string(str(id))
                + "',0,0,NOW(),NOW())"
            )
            execute_sql(sqlFailed, connection)
Example #7
1
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 #8
1
    def __createInsertString__(
        self, jobID, pdbID, dateString, scan, stability, binding, metadata, optionArgs, fileArgs
    ):

        """Creates an SQL insert statement based on the provided data.
		
		Note: The table has five columns - JobID, Date, Stability, Scan and Binding.
		The last three are bools which are set to one if the corresponding entry is
		present in the calculations list.
		
		Parameters:
			jobID: The id for the job
			date: The date for the entry as a string in the format yyyy-mm-dd hh:mm:ss"""

        data = SerializeDictionary(metadata)
        data = MySQLdb.escape_string(data)

        optionArgs = SerializeDictionary(optionArgs)
        optionArgs = MySQLdb.escape_string(optionArgs)

        fileArgs = SerializeDictionary(fileArgs)
        fileArgs = MySQLdb.escape_string(fileArgs)

        data = [self.jobTable, jobID, pdbID, dateString, scan, stability, binding, data, optionArgs, fileArgs]

        insertData = (
            """INSERT INTO %s (JobID, PDBID, Date, Scan, Stability, Binding, Metadata, OptionArguments, FileArguments) VALUES ('%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s')"""
            % tuple(data)
        )

        return insertData
Example #9
1
    def __insert_user_info(self, tweet):
        """ Insert user info into db.
            
            Args:
            tweet: Tweet object containing parsed tweet
        """

        try:
            sql = "INSERT INTO user_info VALUES" "(%d, '%s', '%s', %d, %d, '%s', '%s', '%s', '%s')" % (
                tweet["user"]["user_id"],
                MySQLdb.escape_string(tweet["user"]["screen_name"].encode("utf-8").strip()),
                MySQLdb.escape_string(tweet["user"]["name"].encode("utf-8").strip()),
                tweet["user"]["followers_count"],
                tweet["user"]["friends_count"],
                MySQLdb.escape_string(tweet["user"]["description"].encode("utf-8").strip()),
                MySQLdb.escape_string(tweet["user"]["image_url"].encode("utf-8").strip()),
                tweet["user"]["created_at"].strftime("%Y-%m-%d %H:%M:%S"),
                MySQLdb.escape_string(tweet["user"]["location"].encode("utf-8").strip()),
            )

            self.cursor.execute(sql)

        except Exception, e:
            if "or read-only" not in str(e) and "1062" not in str(e):
                self.print_err("__insert_info", str(e))
Example #10
0
def create_order_exchange_code(order):
    stmt = (
        "INSERT INTO order_exchange_code \
                SET userid = %d, \
                device_id = '%s', \
                serial_num = '%s', \
                money = %d, \
                status = %d, \
                exchange_type = %d, \
                exchange_code = '%s', \
                create_time = NOW(), \
                confirm_time = NOW(), \
                operate_time = NOW()"
        % (
            order.userid,
            MySQLdb.escape_string(order.device_id),
            MySQLdb.escape_string(order.serial_num),
            order.money,
            order.status,
            order.exchange_type,
            MySQLdb.escape_string(order.exchange_code),
        )
    )
    logger.debug(stmt)
    conn.ping(True)
    cur = conn.cursor()
    cur.execute(stmt)
    conn.commit()
Example #11
0
def store_comment(user_name, message, md5):

    # To initial connection
    conn = init_connection()

    # To get current cursor
    cur = conn.cursor()

    user_name = MySQLdb.escape_string(user_name)

    # This set of codes is to get the current user indexID

    # To execute the generated sql text

    cur.execute("""select indexID from users where uName = %s""", user_name)

    # To get one set of data from the return results
    uID = cur.fetchone()

    # To convert format from tuple to string

    uID = str(uID)

    # To split out the user ID from the return results
    uID = uID[1 : +uID.find("L", 1, -1)]

    # This set of codes is to get the supported website indexID

    # To execute the generated sql text
    cur.execute("""select indexID from url where md5 = %s""", md5)

    # To get one set of data from the return results
    urlID = cur.fetchone()

    # To convert format from tuple to string
    urlID = str(urlID)

    # To split out the supported website indexID from the return results
    urlID = urlID[1 : +urlID.find("L", 1, -1)]

    # To execute the generated sql text
    sql = """insert into comments values(null,%s,%s,now(),%s)"""

    message = MySQLdb.escape_string(message)
    args = int(urlID), message, int(uID)

    # To execute the sql
    cur.execute(sql, args)

    # To commit the actions, if not, it will not execbte anything
    conn.commit()

    # To close the current cursor
    cur.close()

    # To kill the connection
    conn.close()

    # To return something
    return "store sucessfully!"
Example #12
0
def updateFileLocation2(src, dst, unitPath, unitIdentifier, unitIdentifierType, unitPathReplaceWith):
    """Dest needs to be the actual full destination path with filename."""
    srcDB = src.replace(unitPath, unitPathReplaceWith)
    dstDB = dst.replace(unitPath, unitPathReplaceWith)
    sql = (
        "SELECT Files.fileUUID, Files.currentLocation FROM Files WHERE removedTime = 0 AND Files.currentLocation = '"
        + MySQLdb.escape_string(srcDB)
        + "' AND "
        + unitIdentifierType
        + " = '"
        + unitIdentifier
        + "';"
    )
    rows = databaseInterface.queryAllSQL(sql)
    if len(rows) != 1:
        print sys.stderr, len(rows), "rows", sql, rows
        exit(4)
    for row in rows:
        fileUUID = row[0]
        location = row[1]
        sql = """UPDATE Files SET currentLocation='%s' WHERE fileUUID='%s';""" % (
            MySQLdb.escape_string(dstDB),
            fileUUID,
        )
        databaseInterface.runSQL(sql)
    print "moving: ", src, dst
    shutil.move(src, dst)
Example #13
0
    def from_analytical(self, identifier):
        """ Return project from analytical database
        """
        query = (
            """
        SELECT identifier, project_name, author, created,
               updated, published, project_key
        FROM project_dim
        WHERE identifier = '%s' AND VALID_TO IS NULL"""
            % identifier
        )

        row = []
        with analytical_query() as cursor:
            try:
                cursor.execute(query)
                row = cursor.fetchone()
            except:
                conf.log.exception("Getting project from analytical db failed. project identifier : %s" % identifier)

        if not row:
            return None

        project = {
            "identifier": MySQLdb.escape_string(row[0]),
            "project_name": MySQLdb.escape_string(row[1]),
            "author": MySQLdb.escape_string(row[2]),
            "created": row[3],
            "updated": row[4],
            "published": row[5],
            "project_key": row[6],
        }
        return project
def BuildASUpdateFieldAndValues(uuid, iso, extra=None):

    if not extra:
        extra = {}
    v1 = iso.getBitsAndValues()
    field_list = ""

    fields_in_row = 0
    for v in v1:

        try:
            field_name = AS2805_to_DB[v["bit"]]
            if field_list != "":
                fields_in_row += 1
                field_list += " , "
            # Add a new line every 5 fields.
            if fields_in_row >= 5:
                field_list += "\n  "
                fields_in_row = 0
            field_list += field_name + '="' + MySQLdb.escape_string(v["value"]) + '"'
        except KeyError as e:
            print "Bit does not exist in the database: " + str(e)

    for extra_field in extra.keys():
        # field_list += ',\n  %s' % extra_field
        v = str(extra[extra_field])
        field_list += ", " + extra_field + '="' + MySQLdb.escape_string(v) + '"'

    sql = "UPDATE host_node SET "
    sql += field_list
    sql += " WHERE tran_gid " + '="' + uuid + '"'

    return sql
Example #15
0
def login():
    username = str(MySQLdb.escape_string(request.form["username"]))
    password = str(MySQLdb.escape_string(request.form["password"]))

    app.logger.debug("login button clicked")
    # check for existing user record in table USERS

    cursor.execute("""SELECT * FROM USERS WHERE USER_NAME = %s""", username)
    app.logger.debug(cursor._executed)
    db.commit()

    row = cursor.fetchone()
    app.logger.debug(row)
    if row:
        pw_hash = row[2]
        # check if password matches
        if bcrypt.check_password_hash(pw_hash, password):
            app.logger.debug("password found")
            setLoginStatus(str(row[0]), 1)
            jsonResponse = {}
            jsonResponse["links"] = dbLinksToDict(str(row[0]))
            jsonResponse["success"] = True
            jsonResponse["username"] = str(row[1])
            resp = Response(json.dumps(jsonResponse), mimetype="application/json")
            # resp = jsonify(success=True, username=username, links=jsonLinks))
            resp.set_cookie("userId", str(row[0]))
            return resp
        else:
            app.logger.debug("password not found")
            return make_response(jsonify(success=False, reason="Password does not match our records"))
    else:
        app.logger.debug("username not found in database")
        return make_response(jsonify(success=False, reason="Username does not match our records"))
Example #16
0
def shorten_url():
    """Set or update the URL to which this resource redirects to. Uses the
    `url` key to set the redirect destination."""
    # user can only add links if logged
    if "userId" in request.cookies:
        user_id = request.cookies["userId"]
        if user_id != "":
            short_url = str(MySQLdb.escape_string(request.form["short-url"]))
            long_url = str(MySQLdb.escape_string(request.form["long-url"]))
            timestamp = datetime.datetime.now()
            click_count = 0
            title = get_url_title(long_url)

            # check if short url is unique
            if checkUniqueShortUrl(short_url):
                # insert url guys to mysql database
                addNewLinkToDB(user_id, short_url, long_url, click_count, timestamp)
                return jsonify(
                    success=True,
                    shortUrl=short_url,
                    longUrl=long_url,
                    timeStamp=timestamp,
                    clickCount=click_count,
                    title=title,
                )
            else:
                return jsonify(success=False, reason="short url not unique")
        else:
            return jsonify(success=False, reason="user not logged in")
    else:
        # return indication that user needs to sign in operation failed
        return jsonify(success=False, reason="user not logged in")
Example #17
0
    def save_data(self, remarks, xmlid, langid, keymask, translation, thekeys, audiofile, status=1):
        if thekeys == None or len(thekeys) == 0:
            return """Field cannot be empty.  Press the back button to try again."""

        table = langid.replace("-", "_")
        if thekeys != "XXXX":
            # force single characters to be upper-case
            if len(thekeys) == 1:
                actualkeys = keymask + thekeys.upper()
            else:
                actualkeys = keymask + thekeys
        else:
            actualkeys = keymask
        (is_valid, msg) = self.validate_single_item(actualkeys, xmlid, langid)
        self.error, self.error_id = msg, xmlid
        if is_valid:
            request = """UPDATE %(table)s SET status="%(status)s",
                textstring="%(textstring)s", remarks="%(remarks)s", 
                actualkeys="%(actualkeys)s" WHERE xmlid="%(xmlid)s" """ % {
                "table": table,
                "status": status,
                "actualkeys": MySQLdb.escape_string(actualkeys),
                "remarks": MySQLdb.escape_string(remarks),
                "xmlid": xmlid,
                "textstring": MySQLdb.escape_string(translation),
            }
            self.session.execute_query(request)
            self.show_no_conflicts = False
            if audiofile != None and audiofile != "" and audiofile.filename != "":
                self.save_audio(audiofile, langid, xmlid)
        self.redirect(xmlid)
Example #18
0
File: qq.py Project: huiwq1990/3gqq
def feedback():
    db = init_db()
    nickname = request.form.get("nickname", "这个人很懒什么都没留下").strip()  # T_T  这样不管用,,当为空时得到的就是空字符串,,,我这个傻逼
    contact = request.form.get("contact", "这个人很懒什么都没留下").strip()
    comment = request.form.get("comment", "妈蛋, 这个人什么都没写").strip()

    if not nickname:
        nickname = "这个人很懒什么都没留下"
    if not contact:
        contact = "这个人很懒什么都没留下"
    if not comment:
        comment = "妈蛋,这个人太懒了吧! 什么都没写..."

    import MySQLdb

    nickname = MySQLdb.escape_string(nickname)
    contact = MySQLdb.escape_string(contact)
    comment = MySQLdb.escape_string(comment)
    sql = r"""
                insert feedback (nickname, contact, comment) values ("%s", "%s", "%s");
        """ % (
        nickname,
        contact,
        comment,
    )
    cursor = db.cursor()
    cursor.execute(sql)
    db.commit()
    db.close()
    return r"""
Example #19
0
def inser_question(data, q_id, cat_id):
    if data[6] == "":
        data[6] = "NULL"
    if data[7] == "N/A":
        data[7] = "NULL"
    print 'INSERT INTO question VALUES (NULL, "' + MySQLdb.escape_string(data[8]) + '", "' + data[5] + '", "' + data[
        7
    ] + '", ' + data[6] + ", NULL, " + cat_id + ")"
    cur.execute(
        'INSERT INTO question VALUES (NULL, "'
        + MySQLdb.escape_string(data[8])
        + '", "'
        + data[5]
        + '", "'
        + data[7]
        + '", '
        + data[6]
        + ", NULL, "
        + cat_id
        + ")"
    )
    db.commit()
    qu_id = cur.lastrowid
    cur.execute("INSERT INTO questionnaire_question VALUES (NULL, " + str(q_id) + ", " + str(qu_id) + " )")
    db.commit()
Example #20
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 #21
0
    def __make_update_sqls(self, data_ls):
        if not data_ls:
            return

        strip_dic_list(data_ls)

        values_ls = []
        for data in data_ls:
            assert self.key_field in data

            set_str_ls = []
            for field, value in data.items():
                if field not in self.field_info_dic:
                    continue

                field_info = self.field_info_dic[field]

                if field == self.key_field:
                    continue

                if is_db_string(field_info["DATA_TYPE"]):
                    set_str_ls.append("%s='%s'" % (field, MySQLdb.escape_string(str(value))))
                else:
                    set_str_ls.append("%s=%s" % (field, value))

            kft = self.field_info_dic[self.key_field]["DATA_TYPE"]
            key_str = ("%s='%s'" if kft else "%s=%d") % (
                self.key_field,
                MySQLdb.escape_string(str(data[self.key_field])),
            )
            set_str = ",".join(set_str_ls)
            values_ls.append("UPDATE %s SET %s WHERE %s" % (self.table_name, set_str, key_str))
        return values_ls
Example #22
0
    def post(self):
        title = self.get_argument("title", None)
        if not title:
            tid = self.get_argument("tid", None)
            if not tid:
                return self.render("error.html", msg="no id")
            done = self.get_argument("done", None)
            if done:
                self.db.update_task(tid=tid, done=done)
                return self.render("success.html")

            content = self.get_argument("content", None)
            if content:
                self.db.update_task(tid=tid, content="'%s'" % MySQLdb.escape_string(content.encode("utf-8")))
                return self.render("success.html")

            order = self.get_argument("order", None)
            if order:
                self.db.update_task(tid=tid, ord=self.db.min_task_ord().get("ord", 0) - 1)
                return self.render("success.html")

        if self.db.find_task(title):  # dump task
            return self.render("error.html", msg="Dump")
        else:  # create task
            self.db.create_task(
                int(time.time()),
                self.db.max_task_ord().get("ord", 0) + 1,
                MySQLdb.escape_string(title.encode("utf-8")),
                "",
                0,
            )
            return self.render("success.html")
Example #23
0
def insertMySQL(tweetDict):
    con = None
    try:
        con = mdb.connect("localhost", "root", "sa", "tweetsearch")
        cur = con.cursor()
        with con:
            cur = con.cursor()
            checkquery = (
                "SELECT * FROM tweet WHERE username = '"
                + MySQLdb.escape_string(tweetDict.keys()[0])
                + "' AND tweetcontent = '"
                + MySQLdb.escape_string(tweetDict.get(tweetDict.keys()[0]))
                + "'"
            )
            cur.execute(checkquery)
            rows = cur.fetchall()
            if len(rows) == 0:
                query = (
                    "INSERT INTO tweet(username, tweetcontent) VALUES('"
                    + MySQLdb.escape_string(tweetDict.keys()[0])
                    + "', '"
                    + MySQLdb.escape_string(tweetDict.get(tweetDict.keys()[0]))
                    + "')"
                )
                cur.execute(query)
                return True
    except mdb.Error, e:
        print "Error %d: %s" % (e.args[0], e.args[1])
        sys.exit(1)
Example #24
0
def update_offerwall_point(device_id, type, increment):
    stmt = "SELECT point FROM offer_wall_point WHERE device_id = '%s' AND type = %d" % (
        MySQLdb.escape_string(device_id),
        type,
    )
    logger.debug(stmt)
    conn.ping(True)
    conn.autocommit(False)
    cur = conn.cursor()
    n = cur.execute(stmt)
    if n == 0:
        stmt = (
            "INSERT INTO offer_wall_point \
                    SET device_id = '%s', type = %d, point = %d, create_time = NOW()"
            % (MySQLdb.escape_string(device_id), type, increment)
        )
        logger.debug(stmt)
        cur.execute(stmt)
        conn.commit()
        return increment
    else:
        res = cur.fetchone()
        stmt = "UPDATE offer_wall_point SET point = %d WHERE device_id = '%s' AND type = %d" % (
            increment,
            MySQLdb.escape_string(device_id),
            type,
        )
        logger.debug(stmt)
        cur.execute(stmt)
        conn.commit()
        return int(res[0]) + increment
Example #25
0
    def __insert_urls(self, tweet):
        """ Insert urls into db.
            
            Args:
            tweet: Tweet object containing parsed tweet
        """

        sql = "INSERT INTO tweet_links VALUES(%d, %d, '%s', '%s', '%s')"

        # insert urls
        try:
            for url in tweet["tweet"]["urls"]:
                if url is None or url == "":
                    continue

                tmp_sql = sql % (
                    tweet["tweet"]["tweet_id"],
                    tweet["user"]["user_id"],
                    MySQLdb.escape_string(self.__expand_url(url["expanded_url"])),
                    MySQLdb.escape_string(url["url"]),
                    tweet["tweet"]["created_at"].strftime("%Y-%m-%d %H:%M:%S"),
                )

                self.cursor.execute(tmp_sql)

        except Exception, e:
            if "or read-only" not in str(e) and "1062" not in str(e):
                self.print_err("__insert_urls", str(e))
Example #26
0
def insert_course(con, name, course_code, level, program_code):
    """Insert the course in the database given the database.
    """
    course_id = get_course_id(con, name)
    if course_id == 0:
        faculty_id = insert_faculty(con, program_code)
        try:
            cur = con.cursor()
            cur.execute(
                """INSERT INTO courses 
                           (
                                name, 
                                course_code, 
                                level, 
                                facultyId
                            ) 
                            VALUES 
                            (
                                '%s', '%s', 
                                '%s', %d
                            )"""
                % (mdb.escape_string(name), mdb.escape_string(course_code), mdb.escape_string(level), faculty_id)
            )
            course_id = cur.lastrowid
            con.commit()
        except mdb.Error, e:
            print "Error %d: %s" % (e.args[0], e.args[1])
Example #27
0
def addRoutes(name, lattitudeStart, longitudeStart, lattitudeEnd, longitudeEnd, isAccessible, transport):
    cleanName = str(MySQLdb.escape_string(name))
    cleanTransport = str(MySQLdb.escape_string(transport))
    isAccessible = str(MySQLdb.escape_string(isAccessible)).upper()
    cur = db.cursor()
    cur.execute("SELECT * FROM routes WHERE name = '" + cleanName + "'")
    if cur.rowcount == 0:
        cur.execute(
            "INSERT INTO routes VALUES('"
            + cleanName
            + "',"
            + lattitudeStart
            + ","
            + longitudeStart
            + ","
            + lattitudeEnd
            + ","
            + longitudeEnd
            + ","
            + isAccessible
            + ",'"
            + cleanTransport
            + "')"
        )
        cur.close()
        return "success"
    else:
        cur.close()
        return "error_exists"
Example #28
0
    def get_saler_target_list_by_condition(self, page_num, per_page, create_user, beg_date, end_date):
        where = ""

        """SQL防注入"""
        create_user = MySQLdb.escape_string(create_user)
        beg_date = MySQLdb.escape_string(beg_date)
        end_date = MySQLdb.escape_string(end_date)

        if create_user != 0:
            where += "create_user=%s and " % create_user
        if beg_date != "0" and end_date != "0":
            where += "create_date between %s and %s and " % (beg_date, end_date)
        elif end_date == "0":
            where += "create_date>=%s and " % beg_date
        elif beg_date == "0":
            where += "create_date<=%s and " % end_date

        where += "1=1"

        result = pager.result_paged(
            "product", where=where, order="product_create_date DESC", page_num=page_num, per_page=per_page
        )

        """替换结果集中的人员id"""
        for item in result:
            id = item.create_user
            item.create_user = users.get_users_by_id(id)[0]["real_name"]

        return result
Example #29
0
def updateDirectoryLocation(src, dst, unitPath, unitIdentifier, unitIdentifierType, unitPathReplaceWith):
    srcDB = src.replace(unitPath, unitPathReplaceWith)
    if not srcDB.endswith("/") and srcDB != unitPathReplaceWith:
        srcDB += "/"
    dstDB = dst.replace(unitPath, unitPathReplaceWith)
    if not dstDB.endswith("/") and dstDB != unitPathReplaceWith:
        dstDB += "/"
    sql = (
        "SELECT Files.fileUUID, Files.currentLocation FROM Files WHERE removedTime = 0 AND Files.currentLocation LIKE '"
        + MySQLdb.escape_string(srcDB)
        + "%' AND "
        + unitIdentifierType
        + " = '"
        + unitIdentifier
        + "';"
    )
    rows = databaseInterface.queryAllSQL(sql)
    for row in rows:
        fileUUID = row[0]
        location = row[1]
        destDB = location.replace(srcDB, dstDB)
        sql = """UPDATE Files SET currentLocation='%s' WHERE fileUUID='%s';""" % (
            MySQLdb.escape_string(destDB),
            fileUUID,
        )
        databaseInterface.runSQL(sql)
    if os.path.isdir(dst):
        if dst.endswith("/"):
            dst += "."
        else:
            dst += "/."
    print "moving: ", src, dst
    shutil.move(src, dst)
Example #30
0
def update_profilers_in_db(profilers, verbose=False, description="NA", add_noncompliant=False):
    """Update profilers in autotest_web database"""
    connection = db_connect()
    cursor = connection.cursor()
    for profiler in profilers:
        name = os.path.basename(profiler).rstrip(".py")
        if not profilers[profiler]:
            if add_noncompliant:
                doc = description
            else:
                print "Skipping %s, missing docstring" % profiler
        else:
            doc = profilers[profiler]
        # check if test exists
        sql = "SELECT name FROM profilers WHERE name='%s'" % name
        cursor.execute(sql)
        results = cursor.fetchall()
        if results:
            sql = "UPDATE profilers SET name='%s', description='%s' " "WHERE name='%s'"
            sql %= (MySQLdb.escape_string(name), MySQLdb.escape_string(doc), MySQLdb.escape_string(name))
        else:
            # Insert newly into DB
            sql = "INSERT into profilers (name, description) VALUES('%s', '%s')"
            sql %= (MySQLdb.escape_string(name), MySQLdb.escape_string(doc))

        db_execute(cursor, sql)

    connection.commit()
    connection.close()