---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------
今天就自己在Ado.net的基础学习中遇到的问题做一下总结。
学习开始阶段就遇到很大麻烦,环境配置连接数据库一直出错。使用的工具是VS2010(旗舰版) 和SQLserver2008。
调试运行弹出警告“ 此版本的 SQL Server 不支持用户实例登录标志。该连接将关闭。”static void Main(string[] args) { string dataDir = AppDomain.CurrentDomain.BaseDirectory; if (dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\")) { dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName; AppDomain.CurrentDomain.SetData("DataDirectory", dataDir); } SqlConnection conn = new SqlConnection(@"Data Source=20111226-1125;AttachDbFilename=|DataDirectory|\CallCenter.mdf;Integrated Security=True;User Instance=True"); conn.Open(); Console.WriteLine("打开数据库连接成功"); Console.ReadKey(); }
开始一直以为是数据库没有装对,或是代码没写对。
最后发现是自己添加数据库的时候出错了。在vs2010的项目中添加数据库时,弹出:
这时候直接取消就是了,不要再选择,要不跟着视频学习时会相当的悲剧的哟,各种问题接踵而至······
直接建好数据库,这种是离线的,方便教学与学习。
还有一件很重要的事,在这一段的学习中,代码中不能忘记加上
string dataDir = AppDomain.CurrentDomain.BaseDirectory; if (dataDir.EndsWith(@"\bin\Debug\") || dataDir.EndsWith(@"\bin\Release\")) { dataDir = System.IO.Directory.GetParent(dataDir).Parent.Parent.FullName; AppDomain.CurrentDomain.SetData("DataDirectory", dataDir); }
这段代码能保证你的操作能影响到当下的数据库,否则即使代码没错,你在数据库中也不会看到更新的数据。
以上是在学习之前需要解决的一点小问题。接下来的学习一切正常,没有遇到大的问题。
在写登录程序时我们应该注意注入漏洞攻击,提倡使用参数化查询。
含有漏洞的代码:
cmd.CommandText = "select count(*) from T_Users where Username='" + username + "' and Password='"+password+"'";
如果登录时输入:1' or '1'='1
那么 :即判定代码变为:Password='1' or '1'='1'
条件永远成立,密码无用,这就是注入漏洞攻击。所以写代码时尤其要注意。应该用参数化的查询方式:cmd.CommandText = "select count(*) from T_Users where Username='" + username + "' and Password='1' or '1'='1'";
cmd.CommandText = "select count(*) from T_Users where Username=@UN and Password=@P"; cmd.Parameters.Add(new SqlParameter("UN", username)); cmd.Parameters.Add(new SqlParameter("P", password)); //初始化字符串,防漏洞
---------------------- Windows Phone 7手机开发、.Net培训、期待与您交流! ----------------------
详细请查看:http://net.itheima.com/