c#代码连接数据库,以及进行crud操作等

在C#的Web.config 里




之间加入下面代码:


 
   
     
   

 

  


 


.cs代码文件里大致总结如下:

 //获取数据库字符串连接字符
    static String strSqlConn = System.Configuration.ConfigurationManager.AppSettings["DbConnString"];

   String sql = "select max(nrow) as maxrow from treenode";
        //using确保资源能被释放//连接数据库
        using ( SqlConnection conn = new SqlConnection(strSqlConn))
        {
            try
            {
                SqlCommand command = new SqlCommand(sql, conn);
                    command.Connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        maxrow = reader.GetInt32(reader.GetOrdinal("maxrow"));

                    }
               
            }
            catch (SqlException ex)
            {
                throw ex;
            }

        }

--------------------------------------------------------------------------------------------------------------------------------------------------

下面是一个具体的.cs连接数据库进行操作的代码源文件

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Data;
///


/// TreeDao 的摘要说明
///

public class TreeDao
{
    //最大的行数
    static int maxrow;
    //获取数据库字符串连接字符
    static String strSqlConn = System.Configuration.ConfigurationManager.AppSettings["DbConnString"];
    //静态的存取删除树根节点的下面节点集合、
    static List list1 = null;
    SqlConnection conns = null;
 
    ///
    /// 查询出最大行数
    ///

    public static int queryMax()
    {
       
        String sql = "select max(nrow) as maxrow from treenode";
        //using确保资源能被释放//连接数据库
        using ( SqlConnection conn = new SqlConnection(strSqlConn))
        {
            try
            {
                SqlCommand command = new SqlCommand(sql, conn);
                    command.Connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                        maxrow = reader.GetInt32(reader.GetOrdinal("maxrow"));

                    }
               
            }
            catch (SqlException ex)
            {
                throw ex;
            }

        }
        return maxrow;
    }
    ///


    /// 将查询出来的所有节点组装成树
    ///

    public static TreeNode assemble(List list)
    {
        //树的最大行
        int c = queryMax();
        //将树的所有节点放入字典里(这里用数据字典就可以避免双重(多重)循环,提高查询效率,避免n次级增长)
        Dictionary d = new Dictionary();
        for (int i = 0; i < list.Count; i++)
        {
            d.Add(list[i].nid, list[i]);
        }
        //从树的最大行开始,直到根节点(寻找绑定儿子节点)
        while (c > 1)
        {
            for (int j = 0; j < list.Count; j++)
            {
                if (list[j].nrow == c)
                {
                    //如果该子节点有父节点
                    if (list[j].pid != null)
                    {
                        //将字典里的父节点的儿子属性集合加上该子节点
                        d[list[j].pid].children.Add(list[j]);
                    }
                }

            }
            c--;
        }
        //取出根节点并将它返回
        for (int k = 0; k < list.Count; k++)
        {
            if (list[k].nrow == 1)
                return d[list[k].nid];

        }
        //如果没有找到根节点就返回Null
        return null;
    }
    ///


    /// 查询出所有的树节点并将之组装成树(调用组装方法)
    ///

           public static TreeNode queryAll()
        {
            List list =new List();
         
            String sql = "select t.nid,"
                         + "t.name,"
                         + "t.nrow,"
                         + "t.pid,"
                         + "t.havechild "
                         + " from treenode t where t.isdelete=0 ";
            //using确保资源能被释放//连接数据库
            using (SqlConnection conn = new SqlConnection(strSqlConn))
            {
                try
                {
                    SqlCommand command = new SqlCommand(sql, conn);
                    command.Connection.Open();
                    SqlDataReader reader = command.ExecuteReader();
                    while (reader.Read())
                    {
                       
                        TreeNode t = new TreeNode();
                       
                        t.nid = reader["nid"].ToString();
                        t.name = reader["name"].ToString();
                        t.nrow = int.Parse(reader["nrow"].ToString());
                        t.pid = reader["pid"].ToString();
                        t.havechild = int.Parse(reader["havechild"].ToString());
                        t.children=new List();
                        list.Add(t);


                    }
                }
                catch (SqlException ex)
                {
                    throw ex;
                }
              
            }
            return assemble(list);
        }
    ///


    /// 删除树叶节点
    ///

           public int deleteNode(String nid)
           {
               int i = 0;
         //需要注意的是SQL SERVER数据库好像支持别名和mysql,oracle有点差异
               //SQL SERVER错误的写法(貌似sqlserver数据库里区分更新前的和更新后的,下面写法会报错)
               //String sql = "update treenode t  set t.isdelete=1  where t.nid=@nid and t.isdelete=0 ";
               //正确的写法如下:
               String sql = "update t  set t.isdelete=1 from treenode t where t.nid=@nid and t.isdelete=0 ";

               //using确保资源能被释放//连接数据库
               using (SqlConnection conn = new SqlConnection(strSqlConn))
               {
                   try
                   {
                       SqlCommand command = new SqlCommand(sql, conn);
                       command.Connection.Open();
                       //指定类型,在C#里可以一定程度上避免sql注入问题
                       SqlParameter p1 = new SqlParameter("@nid",SqlDbType.VarChar);
                       p1.Value = nid;
                       command.Parameters.Add(p1);//添加参数
                       i = command.ExecuteNonQuery();
                   }
                   catch (SqlException ex)
                   {
                       throw ex;
                   }

               }
               return i;
           }
    ///


    /// 删除树根节点的查询
    ///

           public List deleteTreeNode(TreeNode treenode)
           {
             
               List list2 = new List();
               if(list1==null)
               {
                   list1 = new List();
               }
              
               list1.Add(treenode);
               if (conns == null)
                   conns = new SqlConnection(strSqlConn);
               String sql = "select t.nid,t.name,t.nrow,t.havechild,t.pid,t.isdelete from treenode t wheret.pid=@pid and t.isdelete=0 ";
               using(conns){
                   try
                   { 
                       SqlCommand command = new SqlCommand(sql, conns);
                       command.Connection.Open();
                       SqlParameter p1 = new SqlParameter("@pid",SqlDbType.VarChar );
                       p1.Value=treenode.nid;
                       command.Parameters.Add(p1);//添加参数
                       SqlDataReader reader = command.ExecuteReader();
                     while(reader.Read()){
                       TreeNode tt = new TreeNode();
                       tt.nid = reader["nid"].ToString();
                       tt.havechild = int.Parse(reader["havechild"].ToString());
                       list1.Add(tt);
                       list2.Add(tt);
                        }
                   }
                   catch (SqlException ex)
                   {
                       throw ex;
                   }
                   for (int i = 0; i < list2.Count;i++ )
                   {
                       if(list2[i].havechild==1){
                           deleteTreeNode(list2[i]);
                       }
                   }
               }
               return list1;
           }
    ///
    /// 删除树根的实现方法
    ///

           public int deleteAllNode(TreeNode treenode) {
               int sum = 0;
               TreeDao tdao=new TreeDao();
               List oklist = tdao.deleteTreeNode(treenode);
               for (int i = 0; i < oklist.Count;i++ )
               {
                   sum += tdao.deleteNode(oklist[i].nid);
               }
               return sum;
           }
    ///
    /// 修改树节点名称的方法
    ///

           public int updateName(TreeNode treenode) {
               int nuber = 0;
               String sql = "update  t set t.name=@name from treenode t where t.nid=@nid ";
               //using确保资源能被释放//连接数据库
               using (SqlConnection conn = new SqlConnection(strSqlConn))
               {
                   try
                   {
                       SqlCommand command = new SqlCommand(sql, conn);
                       command.Connection.Open();
                       SqlParameter p1 = new SqlParameter("@name",SqlDbType.VarChar );
                       p1.Value=treenode.name;
                       SqlParameter p2 = new SqlParameter("@nid", SqlDbType.VarChar);
                       p2.Value=treenode.nid;
                       command.Parameters.Add(p1);//添加参数
                       command.Parameters.Add(p2);
                       nuber= command.ExecuteNonQuery();
                   }
                   catch (SqlException ex)
                   {
                       throw ex;
                   }

               }
               return nuber;
           }
    ///


    /// 添加树节点的辅助方法-添加子节点成功后修改父节点的havechild状态(将0修改为1,是1就不修改)
    ///

           public int changeHavechild(TreeNode parentnode) {
               int i = 0;
               String sql = "update  t set t.havechild=1 from treenode t where t.nid=@nid ";
               //using确保资源能被释放//连接数据库
               using (SqlConnection conn = new SqlConnection(strSqlConn))
               {
                   try
                   {
                       SqlCommand command = new SqlCommand(sql, conn);
                       command.Connection.Open();
                       SqlParameter p1 = new SqlParameter("@nid",SqlDbType.VarChar );
                       p1.Value=parentnode.nid;
                       command.Parameters.Add(p1);//添加参数
                       i = command.ExecuteNonQuery();
                   }
                   catch (SqlException ex)
                   {
                       throw ex;
                   }

               }
               return i;
           }
    ///


    /// 添加树节点的辅助方法-查询那一层次树节点的数量(为了生成节点id-nid,也可以用UUID,太长不建议)
    ///

           public int queryAddNumber(TreeNode parentnode) {
               int addn = 0;
               String sql = "select count(1) as count from treenode t where t.nrow=@nrow ";
               //using确保资源能被释放//连接数据库
               using (SqlConnection conn = new SqlConnection(strSqlConn))
               {
                   try
                   {
                       SqlCommand command = new SqlCommand(sql, conn);
                       command.Connection.Open();
                       SqlParameter p1 = new SqlParameter("@nrow",SqlDbType.Int );
                       p1.Value=parentnode.nrow;
                       command.Parameters.Add(p1);//添加参数
                       SqlDataReader reader = command.ExecuteReader();
                       while (reader.Read())
                       {
                           addn = reader.GetInt32(reader.GetOrdinal("count"));

                       }
                   }
                   catch (SqlException ex)
                   {
                       throw ex;
                   }

               }
               return addn;
           }
    ///


    /// 添加树节点的辅助方法-查询出此父节点的所有信息
    ///

           public TreeNode queryTreeNode(TreeNode treenode) {
               TreeNode parentnode = new TreeNode();
               String sql = "select t.nid,t.name,t.nrow,t.pid,t.havechild from treenode t wheret.nid=@nid ";
               //using确保资源能被释放//连接数据库
               using (SqlConnection conn = new SqlConnection(strSqlConn))
               {
                   try
                   {
                       SqlCommand command = new SqlCommand(sql, conn);
                       command.Connection.Open();
                       SqlParameter p1 = new SqlParameter("@nid",SqlDbType.VarChar);
                       p1.Value=treenode.nid;
                       command.Parameters.Add(p1);//添加参数
                       SqlDataReader reader = command.ExecuteReader();
                       while (reader.Read())
                       {
                           parentnode.nid = reader["nid"].ToString();
                           parentnode.name = reader["name"].ToString();
                           parentnode.nrow = int.Parse(reader["nrow"].ToString());            
                           parentnode.havechild = int.Parse(reader["havechild"].ToString());
                        

                       }
                   }
                   catch (SqlException ex)
                   {
                       throw ex;
                   }

               }
               return parentnode;
           }

    ///


    /// 添加树节点方法
    ///

           public int addNode(TreeNode treenode) {
               int i = 0;
               //通过混合节点(父节点id和新子节点名字name)查找到父节点信息
               TreeNode parentnode = queryTreeNode(treenode);
               //通过父节点找到子节点所属行的节点数量,以便用于制作子节点nid
               int addn = queryAddNumber(parentnode) + 1;//+1是以1开头
               //父节点所在行为2,找到3层次节点数量5,组成3-6作为新子节点的nid
               String childnid = parentnode.nrow + 1 + "-" + addn;
               String sql = "insert into treenode values(@nid,@name,@nrow,@pid,0,0) ";
               //using确保资源能被释放//连接数据库
               using (SqlConnection conn = new SqlConnection(strSqlConn))
               {
                   try
                   {
                       SqlCommand command = new SqlCommand(sql, conn);
                       command.Connection.Open();
                       SqlParameter p1 = new SqlParameter("@nid", SqlDbType.VarChar);
                       p1.Value = childnid;
                       SqlParameter p2 = new SqlParameter("@name", SqlDbType.VarChar);
                       p2.Value=treenode.name;
                       SqlParameter p3 = new SqlParameter("@nrow",SqlDbType.Int );
                       p3.Value = parentnode.nrow;
                       SqlParameter p4 = new SqlParameter("@pid",SqlDbType.VarChar );
                       p4.Value=parentnode.nid;
                       command.Parameters.Add(p1);//添加参数
                       command.Parameters.Add(p2);//添加参数
                       command.Parameters.Add(p3);//添加参数
                       command.Parameters.Add(p4);//添加参数
                       i = command.ExecuteNonQuery();
                   }
                   catch (SqlException ex)
                   {
                       throw ex;
                   }

               }
               if (parentnode.havechild==0)
               {
                   i = changeHavechild(parentnode);
               }
               return i;
           }
}



你可能感兴趣的:(C#链接数据库)