日期:2009-10-04 浏览次数:20408 次
strConnection = "data source=DBServer;uid=sa;pwd=" |
strSQL = "select sum(cost) from sales where id='" + id + "'"; |
select sum(cost) from sales where id='1' drop table sales -- ' |
[WebMethod] public decimal GetSalesFigures(string CustomerID) { SqlCommand cmd = null; decimal sum = 0.0; try { // 检查CustomerID是否有效,CustomerID必须是二位字符再加6位数字,而且对大小写敏感 Regex reg = new Regex(@"^[a-z]{2}\d{6}$","i"); if (!reg.Match(CustomerID).Success) throw new SoapException("Invalid Sales ID", SoapException.ClientFaultCode); // 从外部位置获取连接字符串 SqlConnection sqlConn= new SqlConnection(ConnectionString); // 向存储过程中添加销售ID string str="spGetSalesFigures"; cmd = new SqlCommand(str,sqlConn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.Add("@ID",CustomerID); cmd.Connection.Open(); sum = (decimal)cmd.ExecuteScalar(); } catch (Exception e) { throw new SoapException(e.Message, SoapException.ClientFaultCode); } finally { // 失败后关闭连接 if (cmd != null) cmd.Connection.Close(); } return sum; } // 从外部XML配置文件获取连接字符串 static internal string ConnectionString { get { XMLTextReader reader = null; string connstring = ""; try { reader = new XMLTextReader (@"c:\config\config.XML"); while (reader.Read()) { if (reader.NodeType == XMLNodeType.Element && reader.Name == "connectstring") { connstring = reader.GetAttribute("value"); } } } finally { if (reader != null) reader.Close(); } return connstring; } } |