ADO.Net_简单的数据源连接

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

namespace MyFirstDB.DB
{
    class DBResources
    {
        //数据库的URL,数据实例,账户密码
        string connString = "Data Source=172.18.19.40;Initial Catalog=Test201209;Persist Security Info=True;User ID=sa;Password=windows";
        //获取连接
        public SqlConnection Connection()
        {
            SqlConnection conn = new SqlConnection(connString);
            try
            {
                conn.Open();
                Console.WriteLine("DB:成功连接");
                return conn;
            }
            catch (Exception e)
            {
                Console.WriteLine("DB:连接异常,{0}", e.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
            return null;

        }

        //关闭连接
        public void close(SqlConnection conn)
        {
            try
            {
                conn.Close();
                conn.Dispose();
            }
            catch (Exception e)
            {
                Console.WriteLine("DB:关闭异常,{0}", e.Message);
            }

        }

        public void GetConnection()
        {
            /* SqlConnection 实现了 DbConnection 抽象类,DbConnection实现了IDisposable接口,
             * 实现了IDisposable接口 可以使用using进行资源管理,在执行完using代码块时系统会自动释放资源
             * 另外,也可以使用传统的try{}...catch(Exception e){}...fianlly{},在fianlly中connection.Close();关闭连接
                connection.Dispose();释放资源
             */
            using (SqlConnection connection = new SqlConnection(connString))
            {

                connection.Open();

                Console.WriteLine("DB:连接成功");
            }

            // 打开数据库连接    

            // 关闭数据库连接    
            //connection.Close();
            Console.WriteLine("DB:关闭成功");
        }

        public void TestConnection()
        {
            Console.WriteLine("DB:测试连接   --------------------------------");
            this.GetConnection();

            Console.ReadKey();
        }
    }
}
 
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值