const char *ADBColumn::insStr() { if (workStr) free(workStr); switch (intDataType) { case FIELD_TYPE_TINY: case FIELD_TYPE_SHORT: workStr = (char *) calloc(32, sizeof(char)); sprintf(workStr, "%d", atoi(intData)); break; case FIELD_TYPE_LONG: workStr = (char *) calloc(32, sizeof(char)); sprintf(workStr, "%ld", atol(intData)); break; case FIELD_TYPE_LONGLONG: workStr = (char *) calloc(64, sizeof(char)); sprintf(workStr, "%qd", atoll(intData)); break; case FIELD_TYPE_DOUBLE: case FIELD_TYPE_FLOAT: workStr = (char *) calloc(64, sizeof(char)); sprintf(workStr, "%f", atof(intData)); break; // Everything else is a string, so escape it and wrap it in quotes. default: if (intIsEncrypted) { workStr = (char *) calloc(16, sizeof(char)); encryptData(); int tmpLen = strlen(workStr); char *tmpStr = (char *) calloc(tmpLen*2+32, sizeof(char)); mysql_escape_string(tmpStr, workStr, tmpLen); free(workStr); workStr = (char *) calloc(strlen(tmpStr)+64, sizeof(char)); strcpy(workStr, "'"); strcat(workStr, tmpStr); strcat(workStr, "'"); free(tmpStr); } else { int tmpLen = 0; if (intData) tmpLen = strlen(intData); workStr = (char *) calloc(tmpLen * 2 + 16, sizeof(char)); char *tmpStr = (char *) calloc(tmpLen * 2 + 16, sizeof(char)); if (intData) mysql_escape_string(tmpStr, intData, tmpLen); strcpy(workStr, "'"); strcat(workStr, tmpStr); strcat(workStr, "'"); free(tmpStr); } break; } return workStr; }
static void convert_line(FILE *sqlfile, char *word, char *meaning) { my_strstrip(meaning, 0, print_info); int word_len = strlen(word); char word_buf[word_len*2+3]; int meaning_len = strlen(meaning); char meaning_buf[meaning_len*2+3]; mysql_escape_string(word_buf, word, word_len); mysql_escape_string(meaning_buf, meaning, meaning_len); fputs("INSERT INTO dict (keyword, definition) VALUES('", sqlfile); fputs(word_buf, sqlfile); fputs("','", sqlfile); fputs(meaning_buf, sqlfile); fputs("');\n", sqlfile); }
/* Add tracks encapsulated in a current_tracks_st to the db. The cd id is * embedded in the current_tracks_st. * Return 1 for success, 0 for error. */ int add_tracks(struct current_tracks_st *tracks) { int res; char is[250]; char es[250]; int i; if (!dbconnected) return 0; // add each track. Note that current_tracks_st *must* have an entry // '\0' at the first byte in order to indicate that we are finished. // Also remember we need to escape the raw inputs. i = 0; while (tracks->track[i][0]) { mysql_escape_string(es, tracks->track[i], strlen(tracks->track[i])); sprintf( is, "INSERT INTO track(cd_id, track_id, title) VALUES(%d, %d, '%s')", tracks->cd_id, i + 1, es ); res = mysql_query(&my_connection, is); if (res) { fprintf(stderr, "Insert error %d: %s\n", mysql_errno(&my_connection), mysql_error(&my_connection)); return 0; } i++; } return 1; }
QString QMYSQLDriver::formatValue( const QSqlField* field, bool trimStrings ) const { QString r; if ( field->isNull() ) { r = nullText(); } else { switch( field->type() ) { case QVariant::ByteArray: { const QByteArray ba = field->value().toByteArray(); // buffer has to be at least length*2+1 bytes char* buffer = new char[ ba.size() * 2 + 1 ]; /*uint escapedSize =*/ mysql_escape_string( buffer, ba.data(), ba.size() ); r.append("'").append(buffer).append("'"); delete[] buffer; } break; case QVariant::String: case QVariant::CString: { // Escape '\' characters r = QSqlDriver::formatValue( field ); r.replace( "\\", "\\\\" ); break; } default: r = QSqlDriver::formatValue( field, trimStrings ); } } return r; }
std::string CPage::getURLsql() const { size_t mxlen = 255; char URLsql[2 * (mxlen + 1)]; // convert the string for inserting int len = mysql_escape_string(URLsql, URL.c_str(), std::min(URL.size(), mxlen)); // terminate the string if( len > 255) { URLsql[255] = '\0'; } else { URLsql[len] = '\0'; } // make sure last char not a \ - it would escape the final quote if( URLsql[254] == '\\') { URLsql[254] = ' '; } else if( URLsql[len-1] == '\\') { URLsql[len-1] = ' '; } return URLsql; }
static void dict_mysql_quote(DICT *dict, const char *name, VSTRING *result) { DICT_MYSQL *dict_mysql = (DICT_MYSQL *) dict; int len = strlen(name); int buflen; /* * We won't get integer overflows in 2*len + 1, because Postfix input * keys have reasonable size limits, better safe than sorry. */ if (len > (INT_MAX - VSTRING_LEN(result) - 1) / 2) msg_panic("dict_mysql_quote: integer overflow in %lu+2*%d+1", (unsigned long) VSTRING_LEN(result), len); buflen = 2 * len + 1; VSTRING_SPACE(result, buflen); #if defined(MYSQL_VERSION_ID) && MYSQL_VERSION_ID >= 40000 if (dict_mysql->active_host) mysql_real_escape_string(dict_mysql->active_host->db, vstring_end(result), name, len); else #endif mysql_escape_string(vstring_end(result), name, len); VSTRING_SKIP(result); }
SQLString * pprepare (char option, SQLString &S, bool replace = true) { if (S.processed) return &S; if (option == 'r' || (option == 'q' && S.is_string)) { char *s = new char[S.size()*2 + 1]; mysql_escape_string(s,const_cast<char *>(S.c_str()),S.size()); SQLString *ss = new SQLString("'"); *ss += s; *ss += "'"; delete[] s; if (replace) { S = *ss; S.processed = true; return &S; } return ss; } else if (option == 'R' || (option == 'Q' && S.is_string)) { SQLString *ss = new SQLString("'" + S + "'"); if (replace) { S = *ss; S.processed = true; return &S; } return ss; } else { if (replace) S.processed = true; return &S; } }
static int sql_escape_binary(void *session, const unsigned char *input, size_t input_size, char **output) { size_t rsize; /* * MySQL documentation say : * The string pointed to by from must be length bytes long. You must * allocate the to buffer to be at least length*2+1 bytes long. (In the * worse case, each character may need to be encoded as using two bytes, * and you need room for the terminating null byte.) */ rsize = input_size * 2 + 3; if ( rsize <= input_size ) return -1; *output = malloc(rsize); if ( ! *output ) return preludedb_error_from_errno(errno); (*output)[0] = '\''; #ifdef HAVE_MYSQL_REAL_ESCAPE_STRING rsize = mysql_real_escape_string((MYSQL *) session, (*output) + 1, (const char *) input, input_size); #else rsize = mysql_escape_string((*output) + 1, (const char *) input, input_size); #endif (*output)[rsize + 1] = '\''; (*output)[rsize + 2] = '\0'; return 0; }
//------------------------------------------------------------------------ SQLQuery& operator << (SQLQuery& o, const mysql_ColData<string>& in) { if (dont_quote_auto) { o << in.get_string(); return o; } if (in.escape_q()) { char *s = new char[in.size()*2+1]; mysql_escape_string(s, const_cast<char *>(in.c_str()), in.size() ); if (in.quote_q()) { o << "'" << s << "'"; } else o << s; delete[] s; } else if (in.quote_q()) { o << "'" << in.get_string() << "'"; } else { o << in.get_string(); } return o; }
// // Return string quoted so it can be used // in database queries. // // NOTE: This function returns a pointer to // a static character buffer. Subsequent calls // overwrite the same buffer so the result must // be copied if it is to be used later. // const char* quote(const char* p) { static string store; int len = 0; if (p != NULL) len = strlen(p); // Allocate space for quoted string, null and // start and end quote char* buf = new char[2 * len + 1 + 2]; if (!buf) return NULL; char* b = buf; // Append one quote at the beginning *buf++ = '\''; if (p != NULL) { mysql_escape_string(buf, p, len); len = strlen(buf); } // Append another quote at the end *(buf + len) = '\''; *(buf + len + 1) = '\0'; store = b; delete [] b; return store.c_str(); }
int add_cd(char* artist, char* title, char* catalogue, int *cd_id){ MYSQL_RES* pRes; MYSQL_ROW rowData; int res, artist_id = -1, new_cd_id = -1; char is[250], es[250]; if (!connected) { return 0; } artist_id = get_artist_id(artist); mysql_escape_string(es, title, strlen(title)); sprintf(is, c2s("insert into cd(title,artist_id, catalogue) values('%s', '%d', '%s')"), es, artist_id, catalogue); res = mysql_query(&mysql, is); if (res){ fprintf(stderr, c2s("Insert error %d: %s\n"), MS_ENO(&mysql), MS_EMSG(&mysql)); return 0; } res = mysql_query(&mysql, c2s("select last_insert_id()")); if (res){ fprintf(stderr, c2s("Select error %d: %s\n"), MS_ENO(&mysql), MS_EMSG(&mysql)); return 0; } else { pRes = mysql_use_result(&mysql); if (pRes){ if ((rowData = mysql_fetch_row(pRes))){ sscanf(rowData[0], "%d", &new_cd_id); } mysql_free_result(pRes); } } *cd_id = new_cd_id; if (new_cd_id != -1) return 1; return 0; }
static const char * driver_mysql_escape_string(struct sql_db *_db, const char *string) { struct mysql_db *db = (struct mysql_db *)_db; size_t len = strlen(string); char *to; if (_db->state == SQL_DB_STATE_DISCONNECTED) { /* try connecting */ (void)sql_connect(&db->api); } if (db->mysql == NULL) { /* FIXME: we don't have a valid connection, so fallback to using default escaping. the next query will most likely fail anyway so it shouldn't matter that much what we return here.. Anyway, this API needs changing so that the escaping function could already fail the query reliably. */ to = t_buffer_get(len * 2 + 1); len = mysql_escape_string(to, string, len); t_buffer_alloc(len + 1); return to; } to = t_buffer_get(len * 2 + 1); len = mysql_real_escape_string(db->mysql, to, string, len); t_buffer_alloc(len + 1); return to; }
size_t Sql_EscapeStringLen(Sql_t* self, char *out_to, const char *from, size_t from_len) { if( self ) return (size_t)mysql_real_escape_string(&self->handle, out_to, from, (uint32)from_len); else return (size_t)mysql_escape_string(out_to, from, (uint32)from_len); }
int find_cds(char* search_str, struct cd_search_st* dest){ MYSQL_RES* pRes; MYSQL_ROW rowData; int res, i = 0, num_rows = 0; char qs[250], ss[250]; if (!connected) return 0; memset(dest, -1, sizeof(CD_SEARCH_ST)); mysql_escape_string(ss, search_str, strlen(search_str)); sprintf(qs, c2s("select distinct artist.id, id.id from artist, cd where artist.id = cd.artist_id and (artist.name like '%%%s%%' or cd.title like '%%%s%%' or cd.catalogue like '%%%s%%'"),ss,ss,ss); res = mysql_query(&mysql, qs); if (res){ fprintf(stderr, c2s("Select error %d: %s\n"), MS_ENO(&mysql), MS_EMSG(&mysql)); } else { pRes = mysql_use_result(&mysql); if (pRes){ num_rows = (int)mysql_num_rows(pRes); if (num_rows > 0){ while ((rowData = mysql_fetch_row(pRes)) && i < MAX_CD_RESULT){ sscanf(rowData[1], "%d", &dest->cd_id[i]); i++; } } mysql_free_result(pRes); } } return num_rows; }
int add_tracks(struct current_tracks_st *tracks) { int res; char is[100]; char es[200]; int i; if (!dbconnected) return 0; i = 0; while (tracks->track[i][0]) { mysql_escape_string(es, tracks->track[i], strlen(tracks->track[i])); sprintf(is, "INSERT INTO track(cd_id, track_id, title) VALUES(%d, %d, '%s')", tracks->cd_id, i + 1, es); res = mysql_query(&my_connection, is); if (res) { fprintf(stderr, "Insert error %d: %s\n", mysql_errno(&my_connection), mysql_error(&my_connection)); return 0; } i++; } return 1; } /* add_tracks */
int find_cds(char *search_str, struct cd_search_st *dest) { MYSQL_RES *res_ptr; MYSQL_ROW mysqlrow; int res; char qs[500]; int i = 0; char ss[100]; int num_rows; if (!dbconnected) return 0; memset(dest, -1, sizeof(*dest)); mysql_escape_string(ss, search_str, strlen(search_str)); sprintf(qs, "SELECT DISTINCT artist.id, cd.id FROM artist, cd WHERE artist.id = cd.artist_id and (artist.name LIKE '%%%s%%' OR cd.title LIKE '%%%s%%' OR cd.catalogue LIKE '%%%s%%')", ss, ss, ss); res = mysql_query(&my_connection, qs); if (res) { fprintf(stderr, "SELECT error: %s\n", mysql_error(&my_connection)); } else { res_ptr = mysql_store_result(&my_connection); if (res_ptr) { num_rows = mysql_num_rows(res_ptr); if ( num_rows > 0) { while ((mysqlrow = mysql_fetch_row(res_ptr)) && i < MAX_CD_RESULT) { sscanf(mysqlrow[1], "%d", &dest->cd_id[i]); i++; } } mysql_free_result(res_ptr); } } return num_rows; } /* find_cds */
unsigned long DBSpool::EscapeString(char* pTo, char* pFrom, unsigned long ulFromLen) { /* if (!m_pSQLConn){ gvLog(LOG_ERR_SYS, "mysql(DBSpool): call Connect() at first!"); return 0; } int iTimes = DB_RECONNECT_TIMES; bool bTest = true; while (mysql_ping(m_pSQLConn)!=0 && iTimes>0){ bTest = false; gvLog(LOG_ERR_SYS, "mysql(DBSpool): connection to database lost, try to connect remain %d times.", iTimes--); if (mysql_real_connect(m_pSQLConn, m_strHost.c_str(), m_strUser.c_str(), m_strPasswd.c_str(), m_strDBname.c_str(), m_shPort, NULL, 0) == NULL){ gvLog(LOG_ERR_SYS, "mysql(DBSpool): connection to database [%s:%d(%s)] failed: %s", m_strHost.c_str(), m_shPort, m_strDBname.c_str(), mysql_error(m_pSQLConn)); }else{ bTest = true; break; } usleep(DB_RECONNECT_TIMEOUT); } if (bTest){ return mysql_real_escape_string(m_pSQLConn, pTo, pFrom, ulFromLen); } */ mysql_escape_string(pTo, pFrom, ulFromLen); return 0; }
void TDatabaseSession::SaveValue( const TStr &Cookie, const TStr &Name, const char *Value, const int Size) { /* NULL ASCII 0. represent this by `\0' \ ASCII 92, Represent this by `\\' ' ASCII 39, Represent this by `\'' " ASCII 34, Represent this by `\"' */ if( Cookie.Length() > 0 ) { query->openSql("SELECT ID FROM tbs_session_blob WHERE FName='"+Name+"' and FCookie='"+Cookie+"' and to_days(fDate) > to_days(now())-"+DaySave); char * s = new char[Size+Size]; mysql_escape_string(s,Value,Size); TStr v(s); delete[] s; if( query->eof() ) query->execSql("INSERT INTO tbs_session_blob (FName,FCookie,FValue,FDate) VALUES ('"+Name+"','"+Cookie+"','"+v+"',now())"); else query->execSql(TStr("UPDATE tbs_session_blob SET FValue='"+v+"', FDate=now() WHERE ID=")+query->fields(0)); query->close(); } }
/// \ingroup waMysqlClient /// \fn string escape_sql( const string &str ) /// SQL语句字符转义 /// \param 要转换的SQL字符串 /// \return 转义过的字符串 string escape_sql( const string &str ) { char *p = new char[str.length()*2+1]; mysql_escape_string( p, str.c_str(), str.length() ); string s = p; delete[] p; return s; }
bool CdbInterface::setTournamentFormat(const string& s) { char query[MAXQUERYSIZE]; memset(query, 0, MAXQUERYSIZE); if (2 * s.size() + 1 >= (MAXQUERYSIZE - 50)) { Sys_LogError("CdbInterface::setTournamentFormat buffer size too small!"); return false; } char* fmt = new char[2 * s.size() + 1]; if (!fmt) { Sys_LogError("CdbInterface::setTournamentFormat out of memory!"); return false; } memset(fmt, 0, 2 * s.size() + 1); mysql_escape_string(fmt, s.c_str(), s.size()); sprintf(query, "UPDATE tournament SET description='%s';", fmt); delete [] fmt; fmt = NULL; if (!dbase_->dbQuery(query)) { Sys_LogError("Query to set tournament format failed."); return false; } return true; }
/// Escapes a string. size_t Sql_EscapeString(Sql* self, char *out_to, const char *from) { if( self ) return (size_t)mysql_real_escape_string(&self->handle, out_to, from, (unsigned long)strlen(from)); else return (size_t)mysql_escape_string(out_to, from, (unsigned long)strlen(from)); }
int add_pc_users(struct pc_users *pn) { MYSQL s; char sql[600]; char newtheme[21]; char newdesc[401]; char newts[20]; char newcorp[81]; newtheme[0]=0; newdesc[0]=0; newts[0]=0; newcorp[0]=0; mysql_init(&s); if (! my_connect_mysql_blog(&s)) { mysql_report_error(&s); return 0; } mysql_escape_string(newtheme, pn->theme, strlen(pn->theme)); mysql_escape_string(newcorp, pn->corpusname, strlen(pn->corpusname)); mysql_escape_string(newdesc, pn->description, strlen(pn->description)); if (pn->uid <= 0) sprintf(sql,"INSERT INTO `users` ( `uid` , `username` , `corpusname` , `description` , `theme` , `nodelimit` , `dirlimit` , `createtime` , `style` , `backimage` , `visitcount` , `nodescount` , `logoimage` , `modifytime` , `links` , `htmleditor` , `indexnodechars` , `indexnodes` , `useremail` , `favmode` , `updatetime` , `userinfor` , `pctype` ,`defaulttopic`) VALUES ('', '%s', '%s', '%s' , 'others', %d, %d, NOW( ) , '0', '' , '0', '0', '' , NOW( ) , '', '1', '600', '5', '', '0', NOW( ) , '' , '0' , '其他类别');",pn->username, newcorp, newdesc, pn->nodelimit, pn->dirlimit); else sprintf(sql,"UPDATE users SET description='%s', corpusname='%s', theme='%s', nodelimit=%d, dirlimit=%d, createtime='%s' WHERE uid=%u AND username='******' ;",newdesc, newcorp, newtheme, pn->nodelimit, pn->dirlimit, tt2timestamp(pn->createtime,newts), pn->uid, pn->username); if (mysql_real_query(&s, sql, strlen(sql))) { mysql_report_error(&s); mysql_close(&s); return 0; } sprintf(sql,"UPDATE newapply SET `apptime` = `apptime` , manager = '%s' , management = 0 WHERE username = '******' ;", getCurrentUser()->userid , pn->username); if (mysql_real_query(&s, sql, strlen(sql))) { mysql_report_error(&s); mysql_close(&s); return 0; } mysql_close(&s); return 1; }
/** * Escapes a string for use in a mysql_query */ static int Lmysql_escape_string (lua_State *L) { const char *unescaped_string = luaL_checkstring (L, 1); unsigned long st_len = strlen(unescaped_string); char to[st_len*2+1]; mysql_escape_string(to, unescaped_string, st_len); lua_pushstring(L, to); return 1; }
void sql_upload (const char *nick, const char *ipaddr, const char *login, const char *path) { char utf8_as_login[128], utf8_as_nick[128], utf8_as_path[MAXPATHLEN*2]; char as_login[128], as_nick[128], as_path[MAXPATHLEN*2]; macroman_to_utf8(login, utf8_as_login, sizeof(utf8_as_login)); macroman_to_utf8(nick, utf8_as_nick, sizeof(utf8_as_nick)); macroman_to_utf8(path, utf8_as_path, sizeof(utf8_as_path)); mysql_escape_string(as_login, utf8_as_login, strlen(utf8_as_login)); mysql_escape_string(as_nick, utf8_as_nick, strlen(utf8_as_nick)); mysql_escape_string(as_path, utf8_as_path, strlen(utf8_as_path)); sql_query("INSERT INTO upload VALUES(NULL,NOW(),'%s','%s','%s','%s')", as_nick, ipaddr, as_login, as_path); }
string CToolKit::EscapeSqlStr(const char *sSrc, int nLen) { char *pBuf = new char[2 * nLen + 1]; unsigned int ret = mysql_escape_string(pBuf, sSrc, nLen); string retStr = string(pBuf, ret); delete [] pBuf; return retStr; }
/* escape_string(string) */ static VALUE escape_string(VALUE klass, VALUE str) { VALUE ret; Check_Type(str, T_STRING); ret = rb_str_new(0, (RSTRING(str)->len)*2+1); RSTRING(ret)->len = mysql_escape_string(RSTRING(ret)->ptr, RSTRING(str)->ptr, RSTRING(str)->len); return ret; }
std::string escapeString(const std::string& from) { char* to = (char*)malloc(2*from.size() + 1); mysql_escape_string(to, from.c_str(), from.size()); std::string res = to; free(to); return res; }
void CPage::SaveCache(ConnectionPtr connection) { Trace("SaveCache", "", m_totalUrlList.size()); // save all the cookies in the current memory list to the database // in the WebPageCookies table ncc::safe_array<char> strQuery(102400); ncc::safe_array<char> sqlCache(40961); { // scope for lock // delete the existing cache in the table for this run snprintf(strQuery, strQuery.size(), SQL_WTT_DEL_CACHE, m_runID); Trace("Query for SaveCache", strQuery, 0); connection->Query(strQuery); try { for (URLList::const_iterator it = m_totalUrlList.begin(); it != m_totalUrlList.end(); ++it) { // convert the string ready to be inserted int len = 0; // convert the string for inserting len = mysql_escape_string(sqlCache, (*it).c_str(),((*it).size()<40960)?((*it).size()):40960); // terminate the string if( len > 40960) { sqlCache[40960] = '\0'; } else { sqlCache[len] = '\0'; } // make sure last char not a \ - it would escape the final quote if( sqlCache[40959] == '\\') { sqlCache[40959] = ' '; } else if( sqlCache[len-1] == '\\') { sqlCache[len-1] = ' '; } // save to the database snprintf(strQuery, strQuery.size(), SQL_WTT_SAVE_CACHE, m_runID, static_cast<const char*>(sqlCache)); Trace("Query for SaveCache", strQuery, 0); connection->Query(strQuery); } } catch (const std::exception& e) { LogError2("SaveCache() - Caught Exception", e.what(), 0, SC_ERR_GROUP_DB, SC_ERR_CODE_STORE_CACHE); } } }
static String HHVM_FUNCTION(mysql_escape_string, const String& unescaped_string) { String new_str((size_t)unescaped_string.size() * 2 + 1, ReserveString); unsigned long new_len = mysql_escape_string(new_str.mutableData(), unescaped_string.data(), unescaped_string.size()); new_str.shrink(new_len); return new_str; }
void sql_query::AddData(char * Field, char * Value) { char tmp_buff[1024]; assert(strlen(Value) < sizeof(tmp_buff)); mysql_escape_string(tmp_buff, Value, strlen(Value)); sprintf(m_Values, "%s, '%s'", m_Values, tmp_buff); AddField(Field); }