嗯,我真的不建議爲此滾動自己的解決方案,但是我會按照問題回答問題。
首先,您需要處理文本並提取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。
什麼是更大的圖片/上下文?你真的想在查詢中包含實際的ID號嗎? – 2011-03-31 15:57:59
'string.Format()'的全部意義在於,您將數據與其用於的字符串表示分開 - 您爲什麼要將它們重新合併到一起? – BrokenGlass 2011-03-31 15:58:18
不知道如何生成要合併的Word文檔(即誰有權訪問它們),我不得不說這似乎是危險的,允許任意SQL被評估或exec'd像那樣.. SQL注入潛伏在那些彎曲的大括號.. – 2011-03-31 16:00:33