C# ADO.NET 对数据库的操作步骤,使用C#对数据库进行增删查改

一、C# 对数据库的操作步骤

1、引入命名空间

 Using System.Data.SqlClient     

2、设置连接字符串

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

//sql 设的字符串名 //server 指服务器:一般是IP地址,本机可以使用点; //database 指数据库名称:要访问的数据库名称            //user 数据库的用户名:一般是sa            //pwd 数据库的密码:自己设置的

3、建立数据库连接对象

SqlConnection conn = new  SqlConnection(sql);

//SqlConnection 连接对象类

4、创建命令对象

SqlCommand cmd = conn.CreateCommand();

//SqlCommand 命令对象类

5、给命令对象写要执行的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';

//CommandText 命令文本

6、打开连接

 conn.Open(); 

7、执行操作,处理数据

(1)查询操作

SqlDataReader  dr  =  cmd.ExecuteReader();  //dr 代表返回的是一个结果集 SqlDataReader 读取器对象类
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("读取失败!");   
}    

(2)增、删、改操作

int   a  =  cmd.ExecuteNonQuery();   //a 返回的是 int 类型,表示几行受影响  
if  ( a > 0 )
{     
    Console.WriteLine("成功");   
 }
else   
{     
    Console.WriteLine("读失败!");   
} 

8、关闭连接 

conn.Close();

注意事项:   

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

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

 使用  break; 跳出循环时,注意跳出后的位置与 conn.Close(); 的关系 。容易出现不经过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
原文地址:https://www.cnblogs.com/Tanghongchang/p/6736098.html