现在我想得到一个在某个城市的员工名字的列表。(就使用SQL-Server预装的Northwind数据库)下面给出最简单的实现: SqlDataAdapter da = new SqlDataAdapter( "SELECT * FROM Employees WHERE City='"+city+"'", nwindConn );DataSet ds = new DataSet(); da.Fill(ds,"Employees"); foreach (DataRow dr in ds.Tables["Employees"].Rows) { string name = dr["LastName"].ToString();int id = (int)dr["EmployeeID"]; Console.WriteLine( id + ": " + name); }
让我们来看看有哪些地方容易出错:1. city参数可能会被SQL注入攻击利用.2. 数据类型是弱类型,需要强制转换类型,容易出现Runtime error.3. 表名和列名都是文字,不是类型变量。编译器无法做检查,容易出现Runtime error. (想必不少人碰到过写错表名,导致数据库访问出错,而debug n久的事情.)4. 查询语句也是文字,同样无法通过编译检查是否出错,容易出现Runtime error.
通过使用SqlParameters以及Typed DataSet我们可以避免前三个问题 SqlDataAdapter da = new SqlDataAdapter( "SELECT * FROM Employees WHERE City= @city", nwindConn ); SqlParameter cityParam = da.SelectCommand.Parameters.Add("@city", SqlDbType.VarChar, 80); cityParam.Value = city; NorthwindDataSet ds = new NorthwindDataSet(); da.Fill(ds, ds.Employees.TableName ); foreach (NorthwindDataSet.EmployeesRow dr in ds.Employees.Rows) { string name = dr.LastName; int id = dr.EmployeeID; Console.WriteLine( id + ": " + name); }
但是第四个问题仍没有解决。也许你想到了 SQL stored procedure,就像下面这样:
CREATE PROCEDURE EmployeesForCity @City nvarchar(80) AS SELECT EmployeeID, LastName FROM Employees WHERE City = @City
SqlCommand cmd = new SqlCommand( "dbo.EmployeesForCity", nwindConn ); cmd.CommandType = CommandType.StoredProcedure; SqlParameter cityParam = cmd.Parameters.Add("@city", SqlDbType.VarChar, 80); cityParam.Value = city; SqlDataAdapter da = new SqlDataAdapter( cmd ); NorthwindDataSet ds = new NorthwindDataSet(); da.Fill(ds, ds.EmployeesForCity.TableName ); foreach (NorthwindDataSet.EmployeesForCityRow dr in ds.EmployeesForCity.Rows) { string name = dr.LastName; int id = dr.EmployeeID; Console.WriteLine( id + ": " + name); }
SQL查询语句虽然不能在编译器检查,但是至少我们可以先在SQL-server中验证stored procedure,再运行我们的程序,比Runtime error好多了。但是万一stored procedure改了,或者是数据库改了,那我们又会看到Runtime error。问题的根本在于我们的代码和数据库的联系实在是太弱了。对于一个小程序就如此容易出现问题,那么对于那种和数据库紧密联系的大型应用就更别谈了。
再来看看C-omega的解决方案: rows = select * from DB.Employees where City == city; foreach( row in rows ) { string name = row.LastName.Value; int id = row.EmployeeID.Value; Console.WriteLine( id.ToString() + ": " + name); }
以上代码需要引起注意的地方:1. 可以将本地变量city直接放入SQL语句,不会被SQL注入攻击。2. 结果集是强类型的,意味着在程序编译的时候我们就知道数据库的结构,甚至可以使用VS.net所带的智能感知(自动完成)功能。3. 在rows以及row前面甚至没有使用类型名,而它们却都是强类型的。4. 不再含有文字类型的信息,避免了人为输入错误。5. 在程序编译的时候就已经和数据库连接,当数据库发生变化的时候,在编译器就会报错。
如果你不喜欢SQL的语法,你甚至用三行代码就能搞定以上所有任务。 DB.Employees [City==city].{ Console.WriteLine( it.EmployeeID + ": " + t.LastName ); };
从c++到C#我们常听见的一句话就是c#是类型安全的。何谓类型安全?就是.Net Runtime支持编译期的类型检查。也就是尽量让Runtime error变成Compile error,可以看出Cω在这个方面更进了一步。
注:鉴于个人水平以及资料方面的原因对其内部机制实现笔者并为做深入研究。
Page rendered at Friday, November 21, 2008 12:54:24 AM (China Standard Time, UTC+08:00)
Disclaimer - 这个Blog是我的个人空间,只代表我个人的看法和言论。 - 拒绝在未经过本人许可的情况下在任何商业性出版物品或商业性网站上引用本站文章。 - 欢迎其他Blogger在自己的Blog中引用我的文章,但请注明Trackback URL。 - 鲁ICP备05009011号