hey,
I have a c# server-side app that has db (mysql), and quite oftenly, due to my DB current schema, i have to retrieve a user’s id by his username in order to manipulate the user’s data (such as editing his profile db tables etc.) .
I was thinking of creating a simple cache class that when it handles a request for a specific username to userid mapping, it caches the result in a dictionary, or even in a dedicated dictionary for the first character of the given username.
Here is an example of what i was thinking:
public class UsernameToIdCache
{
public int GetUserIdFromUsername(string username)
{
if (string.IsNullOrEmpty(username)) return -1;
var targetDictionary = _cacheDictionaries[username[0]];
int id;
if (targetDictionary.TryGetValue(username,out id))
{
return id;
}
else
{
id = RunSqlQuery("select id from users where username ='" + username + "'");
if (IsDictionaryNotFull(targetDictionary))
{
targetDictionary.Add(username,id);
return id;
}
}
}
}
the IsDictionaryNotFull(Dictionary<int,string>) method is used for memory management (i don’t want the dictionaries to explode, so it can only help until the dictionaries are full) .
what do you think?
Is it a good db coding practice ?
Is it ASP.NET app? If so, consider putting ID into Session object. It will be loaded once the user logs in and no other magic cacheing is needed.