110,533
社区成员
发帖
与我相关
我的任务
分享
string sql = "delete form table11 where c2='1;1''';" +
"create table table11(c1 string, c2 string);" +
"insert into table11(c1, c2) values('1;abdc;e''fg', 'b');" +
"insert into table11(c2, c1) values('er;create table 2', 'z')";
if (sql.Substring(sql.Length - 1) != ";")
sql += ";";
char[] chSQL = sql.ToCharArray();
bool bFindStr = false;
int nStart = 0 ;
for (int i = 0; i < chSQL.Length; i++)
{
if (chSQL[i] == '\'')
{
if (!bFindStr)
bFindStr = true;
else
{
if (chSQL[i + 1] != '\'')
bFindStr = false;
else
i++;
}
continue;
}
if (!bFindStr && chSQL[i] == ';')
{
Console.WriteLine(sql.Substring(nStart, i - nStart + 1));
nStart = i + 1;
}
}
if(bFindStr)
Console.WriteLine(sql.Substring(nStart));
}
//原字符串
private static string strSQL =
@"insert into table11(c1, c2) values('1;abdc;e''fg', 'b');delete table table11(c1 string, c2 string);create table table11(c1 string, c2 string);insert into table11(c1, c2) values('1;abdc;e''fg', 'b');drop table s_user";
//设定以以下字符串开头的子句可以作为独立的语句
private static List<string> lstHeaderWord = new List<string>()
{
"create ",
"delete ",
"insert ",
"drop "
};
private static List<string> lstResult = new List<string>();
static void Main(string[] args)
{
//将原字符串按';'分割,加入结果列表
lstResult.AddRange(split(strSQL, ";"));
//将所有分割结果最后附加';'
for (int i = lstResult.Count - 1; i >= 0; i--)
{
lstResult[i] += ";";
}
//遍历结果列表
for (int i = lstResult.Count - 1; i > 0; i--)
{
//如果语句的开头不是允许的语句开头
if (!startWithHeaderWord(lstResult[i]))
{
//将该条语句附加至上一条语句的末尾
lstResult[i - 1] += lstResult[i];
//删除该条的语句
lstResult.RemoveAt(i);
}
}
//输出结果
foreach (string s in lstResult)
{
Console.WriteLine(s);
}
Console.Read();
}
/// <summary>
/// 指示制定的语句头是否可以作为独立的语句
/// </summary>
/// <param name="sentence"></param>
/// <returns></returns>
static bool startWithHeaderWord(string sentence)
{
foreach (string s in lstHeaderWord)
{
if (sentence.StartsWith(s))
{
return true;
}
}
return false;
}
/// <summary>
/// 纯粹为了简化String.Split(String[],StringSplitOptions)
/// </summary>
/// <param name="sentence"></param>
/// <param name="word"></param>
/// <returns></returns>
static string[] split(string sentence, string word)
{
return sentence.Split(new string[] { word }, StringSplitOptions.RemoveEmptyEntries);
}
Regex reg = new Regex(@"(?is)(\([^()]*\)|[^;()]+)*;");
MatchCollection mc = reg.Matches(yourStr);
foreach (Match m in mc)
{
richTextBox2.Text += m.Value + "\n";
}
/*-----输出-----
create table table11(c1 string, c2 string);
insert into table11(c1, c2) values('1;abdc;e''fg', 'b');
insert into table11(c2, c1) values('2', 'z');
*/
如果()有嵌套的话,也可以做,只不过正则复杂一些
以上只是针对相对简单的情况,SQL有些情况下还是比较复杂的,如果这时要进行分割,就必须得有明确的规则支持了