zoukankan      html  css  js  c++  java
  • 数据库连接的九大步骤

    连接数据库的九个步骤

    1、引入命名空间    using System.Data.SqlClient;

    2、定义连接字符串    1)SQL Server 身份认证  

                string conString="Data Source=服务器名;    Initial Catalog=数据库名; User ID=sa;pwd=123"   

               2)Window身份认证    

              string conString="Data Source=服务器名;    Initial Catalog=数据库名;Integrated Security=True";   

              3)另一种写法    

              string conString="server=服务器名;database=数据库名;  uid=用户名;pwd=密码";

    3、创建Connection对象    SqlConnection conn=new SqlConnection(连接字符串);

    4、打开数据库连接    conn.Open();

    5、定义SQL语句(包含增删改查的SQL语句)    string sql="select COUNT(*) from Admin";//返回单个值

    6、创建Command对象  SqlCommand command=new SqlCommand(sql,conn);

    7、执行SQL语句并返回结果集    /执行包含COUNT(*)的SQL语句    int count=(int)command.ExecuteScalar();    //执行UPDATE DELETE INSERT SQL语句 返回受影响的行数    int rows=command.ExecuteNonQuery();    //读取数据库表中的数据    SqlDataReader reader=command.ExecuteReader();

    8、对结果集进行处理    if(count>0)    {       //    }

    9、关闭数据库连接    conn.Close();  

                注意:只要有数据库操作的代码,务必加上try-catch-finally

                                                 try {   //可能出现异常的代码 }

                    catch(处理异常类型)

                     {   //处理异常的代码 }

                    finally {   //无论是否出现异常都会执行 }

             

  • 相关阅读:
    JSP环境探针-当前电脑所有系统参数
    SqlServer service broker 分布式系统(赵松桃)跳水 2005 数据库编程
    主机Window不能访问该虚拟机Linux Samba文件服务提供了一个文件夹
    hdu 4901 The Romantic Hero
    linux、hdfs、hive、hbase经常使用的命令
    Android 设计模式模式适配器
    PHP扩展memcache模
    算法——字符串匹配Rabin-Karp算法
    三个重要的散列演示
    CodeForces 10C. Digital Root
  • 原文地址:https://www.cnblogs.com/Mindreader/p/4415948.html
Copyright © 2011-2022 走看看