Что ж, я не рекомендую использовать для этого собственное решение, однако я отвечу на вопрос в том виде, в котором он был задан.
Сначала вам нужно обработать текст и извлечь операторы SQL.Для этого вам понадобится простой парсер:
/// <summary>Parses the input string and extracts a unique list of all placeholders.</summary>
/// <remarks>
/// This method does not handle escaping of delimiters
/// </remarks>
public static IList<string> Parse(string input)
{
const char placeholderDelimStart = '{';
const char placeholderDelimEnd = '}';
var characters = input.ToCharArray();
var placeHolders = new List<string>();
string currentPlaceHolder = string.Empty;
bool inPlaceHolder = false;
for (int i = 0; i < characters.Length; i++)
{
var currentChar = characters[i];
// Start of a placeholder
if (!inPlaceHolder && currentChar == placeholderDelimStart)
{
currentPlaceHolder = string.Empty;
inPlaceHolder = true;
continue;
}
// Start of a placeholder when we already have one
if (inPlaceHolder && currentChar == placeholderDelimStart)
throw new InvalidOperationException("Unexpected character detected at position " + i);
// We found the end marker while in a placeholder - we're done with this placeholder
if (inPlaceHolder && currentChar == placeholderDelimEnd)
{
if (!placeHolders.Contains(currentPlaceHolder))
placeHolders.Add(currentPlaceHolder);
inPlaceHolder = false;
continue;
}
// End of a placeholder with no matching start
if (!inPlaceHolder && currentChar == placeholderDelimEnd)
throw new InvalidOperationException("Unexpected character detected at position " + i);
if (inPlaceHolder)
currentPlaceHolder += currentChar;
}
return placeHolders;
}
Хорошо, так что вы получите список операторов SQL, извлеченных из входного текста.Возможно, вы захотите настроить его так, чтобы использовать правильно типизированные исключения синтаксического анализатора и некоторые средства защиты ввода (которые я исключил для ясности).
Теперь вам просто нужно заменить эти заполнители на результаты вычисленного SQL:
// Sample input
var input = "Hello Mr. {select firstname from users where userid=7}";
string output = input;
var extractedStatements = Parse(input);
foreach (var statement in extractedStatements)
{
// Execute the SQL statement
var result = Evaluate(statement);
// Update the output with the result of the SQL statement
output = output.Replace("{" + statement + "}", result);
}
Это, очевидно, не самый эффективный способ сделать это, но я думаю, что он в достаточной мере демонстрирует концепцию, не пачкая воды.
Вам нужно будет определить метод Evaluate(string)
.Это будет обрабатывать выполнение SQL.