日期:2014-05-20  浏览次数:21081 次

(例子)学习ADO.NET3个基础例子
本帖最后由 caozhy 于 2013-03-14 08:05:34 编辑
程序要和数据库交互要通过ADO.NET进行,通过AOD.NET就能在程序中执行SQL了


项目内嵌mdf文件形式的连接字符串  必须加
            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);
            }


ADO.NET经典案例
例1:插入数据:
using (SqlConnection conn = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\C#程序\第二阶段\第二阶段\ADO.NET入门\AOD.net.mdf;Integrated Security=True"))
            {
                conn.Open();
                    using(SqlCommand cmd=conn.CreateCommand())
                    {
                        cmd.CommandText="insert into fuser(username,passwors)values('admin','888');";
                        cmd.ExecuteNonQuery();
                        Console.WriteLine("插入成功");
                    }

            }
            Console.WriteLine("测试正常");
            Console.ReadKey();


列2:登录验证:
Console.WriteLine("输入用户名");
            string username= Console.ReadLine();
            Console.WriteLine("输入密码");
            string password= Console.ReadLine();
            using (SqlConnection coon = new SqlConnection(@"Data Source=(LocalDB)\v11.0;AttachDbFilename=E:\C#程序\第二阶段\第二阶段\ADO.NET入门\AOD.net.mdf;Integrated Security=True"))
            {
                coon.Open();
                using(SqlCommand cmd=coon.CreateCommand())//创建与数据库交谈的命令
                {
                    cmd.CommandText = "select *from fuser where username='"+username+"'";//先到表中查用户输入的用户名对应的信息
                    using( SqlDataReader reader=cmd.ExecuteReader())
                    {
                        if (reader.Read())
                        {
                            //用户名存在
                            string dbpass = reader.GetString(reader.GetOrdinal("passwors"));//比较数据库中记录的密码和用户输入的密码是否一致
                            if (password == dbpass)
                            {
                                Console.WriteLine("登录成功");
                            }