1、把長的SQL語句保存成單獨的文件,如把下面的SQL語句保存成insert_users.sql文件
insert into users(UserName,Sex,Age,Email,Address)
values(''@param000'',''@param001'',''@param002'',''@param003'',''@param004'')
@parm***:代表插入SQL語句的參數
2、以下兩個函數可能在你的項目中經常使用,所以建議寫到公共類裡面,在這裡我定義公共類為DataBase:
public static string readSQL(string filePath, string[] param)
{
FileStream fs = new FileStream(filePath, FileMode.Open);
StreamReader sr = new StreamReader(fs);
string strSql = sr.ReadToEnd();
sr.Close();
fs.Close();
return ArrayReplace(strSql, param);
}
public static string ArrayReplace(string src, string[] param)
{
int ArrayMax = param.Length;
for (int i = 0; i < ArrayMax; i++)
{
string a = i.ToString();
string rep = "@param" + a.PadLeft(3, ''0'');
src = src.Replace(rep, param[i]);
}
return src;
}
3、引用公共類的以上兩個方法,進行SQL語句中參數的值替換,使用如下(常寫在.cs文件中)
public string getSQL()
{
string sqlFileName;
string strResult;
string[] param = new string[5];
try
{
sqlFileN
ame = "users_insert.sql";
strResult = "";
param[0] = txtName.Text.Trim();
param[1] = ddlSex.SelectedIndex.ToString();
param[2] = txtAge.Text.Trim();
param[3] = txtEmail.Text.Trim();
param[4] = txtAddress.Text.Trim();
strResult = DataBase.readSQL(Server.MapPath("sql/")+sqlFileName, param);
}
catch (Exception exGetSql)
{
throw new Exception(exGetSql.Message);
}
return strResult;
}
這樣返回的結果形式如下:
insert into users(UserName,Sex,Age,Email,Address)
values(''jack'',''男'',''24'',''[email protected]'',''深圳市羅湖區'')
這樣的話,當你修改sql語句時只需要修改sql文件(當然前提是參數的個數一定要配對喲),而無需進行程序的再編譯。:)