ADO.NET 【增】【删】【改】【查】

本文详细介绍如何使用SqlConnection, SqlCommand等对象进行数据库的连接、查询、增删改操作,并提供了多个实战案例。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

数据访问

 Using System.Data.SqlClient;   对应命名空间

                                      -- SqlConnection       连接对象

                                      -- SqlCommand         命令对象

                                      -- SqlDataReader      读取器对象

                                      -- CommandText       命令文本

 

1、设置连接字符串

string sql = “ server = . ; database = Data0216 ; user=sa ; pwd = 123  ";

            -- sql               设的字符串名

              -- server         指服务器一般是IP地址本机可以使用点;           

                              -- database     指数据库名称要访问的数据库名称           

                              -- user             数据库的用户名:一般是sa           

                              -- pwd             数据库的密码:自己设置的

2、建立数据库连接

SqlConnection conn = new  SqlConnection(sql);

                                                    -- conn:连接对象名称

3、创建命令对象

SqlCommand cmd = conn.CreateCommand();

                                                    -- cmd:命令对象名称

4、写要执行的SQL语句

       查询

        cmd.CommandText = "select * from Info"; 

    添加

        cmd.CommandText = "Insert into Info values('p032','毒哥','True','n001','1987-02-02')";

    删除

         cmd.CommandText = "delete from Info where Code='p032';

    更改

            cmd.CommandText = "update Info set name='情方方' where Code='p032';

 

5、打开连接

    conn.Open();  

 

6、执行操作,处理数据

   6—1  查询          

      SqlDataReader  dr  =  cmd.ExecuteReader();              -- dr 代表返回的是一个结果集

 

  if (dr.HasRows)                           -- HasRows 判断是否有行数据 bool型,返回true/false   

     {     

                 while(dr.Read())   -- dr.Read() 数据库数据访问指针,每执行一次向下走一行,有内容则返回true,没有返回 false

                     {                          -- dr访问为当前行数据集合,可以使用索引或是列名来访问相对应的数据                                                                            

                         string ids = dr[0].ToString();                                                        
                         string username = dr[1].ToString();
                         string birthday = dr["Birthday"].ToString();
                         string password = dr["PassWord"].ToString();

                    }                      -- 使用while循环读取所有数据,当dr.Read(); 返回值是 false 时跳出循环  

      }   

      else   

      {     

                 Console.WriteLine("读取失败!");   

      }

 6—2  增、删、改  

         int   a  =  cmd.ExecuteNonQuery();                               -- a 返回的是 int 类型,表示几行受影响  

  if  ( a > 0 )

     {     

                 Console.WriteLine("成功");   

     }

    else   

      {     

                 Console.WriteLine("读失败!");   

      }

 

7、关闭连接

       conn.Close();

 

案例1

     查询一个表的所有数据

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.SqlClient;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
             //连接字符串
            string sql = "server=.;database=Data0216;user=sa;pwd=123";

            //创建据库连接
            SqlConnection conn = new SqlConnection(sql);

             //创建命令对象
            SqlCommand cmd = conn.CreateCommand();

            //执行的SQL语句
            cmd.CommandText = "select *from Users";

             打开连接
            conn.Open();

            //执行操作,数据处理
            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.HasRows)
            {
                while (dr.Read())
                {
                    string ids = dr[0].ToString();
                    string username = dr[1].ToString();
                    string birthday = dr["Birthday"].ToString();
                    string password = dr["PassWord"].ToString();
                    string nickname = dr["NickName"].ToString();
                    string sex = dr["Sex"].ToString();
                    string nation = dr["Nation"].ToString();

                    Console.WriteLine(ids + " | " + username + " | " + password + " | " + nickname + " | " + sex + " | " + birthday + " | " + nation);
                }
            }

            //关闭连接
            conn.Close();

            Console.ReadKey();
        }
    }
}
View Code

 

案例2

     删除数据

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            string sql = "server=.;database=Data0216;user=sa;pwd=123";

            SqlConnection conn = new SqlConnection(sql);

            SqlCommand cmd = conn.CreateCommand();

            cmd.CommandText = "delete from users where username='zhangsan'";

            conn.Open();

            int a = cmd.ExecuteNonQuery();

            if (a > 0)
            {
                Console.WriteLine("删除成功,本次共删除" + a + "");
            }

            else
            {
                Console.WriteLine("删除失败,本次未删除任何数据");
            } 

            conn.Close();

            Console.ReadLine();
        }
    }
}
View Code

 

案例3

     修改数据

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {
            bool has = false;

            string sql = "server=.;database=Data0216;user=sa;pwd=123";

            SqlConnection conn = new SqlConnection(sql);

            SqlCommand cmd = conn.CreateCommand();

            Console.Write("请输入要修改的用户的用户名:");
            string name = Console.ReadLine();

            cmd.CommandText = "select *from Users where UserName = '" + name + "'";

            conn.Open();

            SqlDataReader dr = cmd.ExecuteReader();

            if (dr.HasRows)
            {
                has = true;
            }
            conn.Close();

            if (!has)
                Console.WriteLine("用户名输入错误!查无此用户");
            else
            {
                Console.WriteLine("已查询到此用户,请输入更改的信息");
                Console.Write("请输入修改后的密码:");
                string password = Console.ReadLine();
                Console.Write("请输入修改后的昵称:");
                string nickname = Console.ReadLine();
                Console.Write("请输入修改后的性别:");
                string sex = Console.ReadLine();
                Console.Write("请输入修改后的生日:");
                string birthday = Console.ReadLine();
                Console.Write("请输入修改后的民族:");
                string nation = Console.ReadLine();

                cmd.CommandText = "update Users set PassWord='" + password + "',NickName='" + nickname + "',Sex='" + sex + "',Birthday='" + birthday + "',Nation='" + nation + "' where UserName = '" + name + "'";

                conn.Open();

                int aaa = cmd.ExecuteNonQuery();

                conn.Close();

                if (aaa > 0)
                {
                    Console.WriteLine("修改成功");
                }
                else
                {
                    Console.WriteLine("修改失败");
                } 
            }

            Console.ReadLine();

        }
    }
}
View Code

 

案例4

     有条件的添加数据

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Text;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            //编写一个完整的,带限制的添加功能

            string sql = "server=.;database=Data0216_5;user=sa;pwd=123";

            SqlConnection conn = new SqlConnection(sql);

            SqlCommand cmd = conn.CreateCommand();

            #region 添加该用户名

            string name;

            while (true)
            {
                Console.Write("请输入用户名");
                 name = Console.ReadLine();
                //不能为空,不能重复

                if (name.Length == 0)
                {
                    Console.WriteLine("输入错误!用户名不能为空");
                }
                else
                {
                    cmd.CommandText = " select Username from users where Username='" + name + "'";

                    conn.Open();

                    SqlDataReader dr = cmd.ExecuteReader();

                    if (dr.HasRows)
                    {
                        Console.WriteLine("输入错误!该用户已存在");
                    }
                    else
                    {
                        break;
                    }

                  


                }

            }

            conn.Close();
            #endregion

            #region 添加密码

            string password;
            while (true)
            {
                Console.Write("请输入密码(6位以上数字字母):");
                password = Console.ReadLine();
                //不能小于6位

                if (password.Length < 6)
                {
                    Console.WriteLine("输入有误!密码不能小于6位数");
                }
                else
                {
                    break;
                }
            }

            #endregion

            #region 添加昵称

            string nickname;
            while (true)
            {
                Console.Write("请输入昵称:");
                 nickname = Console.ReadLine();
                //不能为空

                if (nickname.Length == 0)
                {
                    Console.WriteLine("昵称不能为空");
                }
                else
                {
                    break;
                }

            }
            #endregion

            #region 添加性别

            string sex; 
            while (true)
            {
                Console.Write("请输入性别(男/女):");
                 sex = Console.ReadLine();
                //让用户输入 男  女

                if (sex == "")
                {
                    sex = "true";
                    break;
                }
                else if (sex == "")
                {
                    sex = "false ";
                    break;
                }
                else {
                    Console.WriteLine("输入有误!性别只有<男/女>");
                }
            }
            #endregion

            #region 添加生日

             string birthday;
            while (true)
            {
                Console.Write("请输入生日:");
                 birthday = Console.ReadLine();
                //日期格式是否正确
                try
                {
                    DateTime dt = new DateTime();
                    dt = Convert.ToDateTime(birthday);
                    break;
                }
                catch
                {
                    Console.WriteLine("日期格式不正确");
                }
            }

            #endregion

            #region 添加名族

             string nation;
     
            while (true)
            {
                Console.Write("请输入民族:");
                 nation = Console.ReadLine();
                //有无此民族

                cmd.CommandText = "select NationCode from usernation  where NationName like '" + nation + "%'; ";

                conn.Open();

                SqlDataReader der = cmd.ExecuteReader();
                if (der.HasRows)                   
                {
                    der.Read();                  
                        nation = der["NationCode"].ToString();
                        break;                  
                }
                else
                {
                    Console.WriteLine("暂无此民族");
                }              

            }
            conn.Close();

            #endregion

            #region 执行添加程序

            cmd.CommandText = "insert into users values('" + name + "','" + password + "','" + nickname + "','" + sex + "','" + birthday + "','" + nation + "')";
            conn.Open();

            int a = cmd.ExecuteNonQuery();
            if (a > 0)
            {
                Console.WriteLine("添加成功!");
            }
            else
            {
                Console.WriteLine("添加失败!!"); 
            }

            conn.Close();

            #endregion

            Console.ReadLine();

        }
    }
}
View Code

 

     conn.Open();

                              -- 每次打开数据库只能执行,增、删、改、查。中的一个

                              -- 注意在有循环运行的时候,尽量避免有频繁的开关数据库,可将开关放到循环外

                              -- 使用  break; 跳出循环时,注意跳出后的位置与 conn.Close(); 的关系 。容易出现不经过conn.Close();,没有关上库。  

     conn.Close();

 

转载于:https://www.cnblogs.com/Tanghongchang/p/6736098.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值