zoukankan      html  css  js  c++  java
  • 步步为营-36-ADO.Net简介

    与数据库进行连接交互

    方法一

      #region 01连接对象
               //01 连接字符串
                string connstr = "server=.;uid=sa;pwd=sa;database=DemoDB;";
                SqlConnection conn = new SqlConnection(connstr);
                conn.Open();
                
                //02 创建sql命令对象
                SqlCommand cmd = new SqlCommand();
                //0201-通过属性 指定连接对象
                cmd.Connection = conn;
                cmd.CommandText = "insert into UserInfo (EmpId, StuName, StuAge, Delflag, ClassNo) values (12,'张三',23,0,1)";
              
                Console.WriteLine("受影响行数{0}",  cmd.ExecuteNonQuery());
                conn.Close();
                #endregion
    View Code

    方法一的弊端就是:需要手动打开关闭数据库,而且还需要try catch 捕获异常,不推荐

    方法二 利用using操作数据库

    using System;
    using System.Collections.Generic;
    using System.Data.SqlClient;
    using System.Linq;
    using System.Text;
    using System.Threading;
    using System.Threading.Tasks;
    
    namespace ADO.NET
    {
        class Program
        {
            static void Main(string[] args)
            {
                #region 01连接对象
               //01 连接字符串
                string connstr = "Data Source=127.0.0.1;uid=sa;pwd=sa;Initial Catalog=DemoDB;";
    
                using ( SqlConnection conn = new SqlConnection(connstr))
                {
    
                    using (SqlCommand cmd = new SqlCommand())
                    {
                        //0201-通过属性 指定连接对象
                        cmd.Connection = conn;
                        conn.Open();
                        cmd.CommandText = "insert into UserInfo (EmpId, StuName, StuAge, Delflag, ClassNo) values (122,'张2三',23,0,1)";
                        Console.WriteLine("受影响行数{0}", cmd.ExecuteNonQuery());
                        
                    }
                 
                #endregion 
                }
    
                Console.Read();
    
            }
        }
    }
    View Code

    其实方法二也有弊端,就是如果有多个类文件的话需要多次编写连接字符串,而且数据库用户名,密码一旦更改需要改动的地方很多.通常是用配置文件进行连接数据库

  • 相关阅读:
    bzoj1923 [Sdoi2010]外星千足虫(gauss)
    bzoj1013 [JSOI2008]球形空间产生器sphere(gauss)
    bzoj1013 [JSOI2008]球形空间产生器sphere(gauss)
    高斯消元(写(shui)题必备)
    随 (rand)(校内hu测10.6T1)(dp+矩阵+数论)
    随 (rand)(校内hu测10.6T1)(dp+矩阵+数论)
    题(problem)(详解10.5hu测T3:Catalan)
    题(problem)(详解10.5hu测T3:Catalan)
    高精度(模板)
    FJUT ACM 2144 并查集
  • 原文地址:https://www.cnblogs.com/YK2012/p/6763515.html
Copyright © 2011-2022 走看看