ADO.NET连接数据库的一个类

2008-07-01  来源:   浏览次数 7

现在C#学到用ADO.NET连接数据库, 我将连接数据库的基本知识附上, 以便加深印象和供以后查阅, 也提供给广大CSDN的朋友们参考, 有错误的地方希望大家不吝赐教. 

  1. using System;   
  2.   
  3. using System.Collections.Generic;   
  4.   
  5. using System.ComponentModel;   
  6.   
  7. using System.Data;   
  8.   
  9. using System.Drawing;   
  10.   
  11. using System.Text;   
  12.   
  13. using System.Windows.Forms;   
  14.   
  15. using System.Data.SqlClient;   
  16.   
  17.   
  18.   
  19. namespace OpenCloseDB   
  20.   
  21. {   
  22.   
  23.     public partial class OpenCloseDB : Form   
  24.   
  25.     {   
  26.   
  27.         public OpenCloseDB()   
  28.   
  29.         {   
  30.   
  31.             InitializeComponent();   
  32.   
  33.         }   
  34.   
  35.   
  36.   
  37.         private void btnTest_Click(object sender, EventArgs e)   
  38.   
  39.         {   
  40.   
  41.             string sqlConnStr = "Data Source = 'MyComputer\\SQLEXPRESS';Initial Catalog = 'UserInfo'; User ID = 'sa'; Pwd = 'MyComputer'";//定义连接字符串   
  42.   
  43.             SqlConnection sqlConn = new SqlConnection(sqlConnStr);//创建 Connection 对象   
  44.   
  45.             try  
  46.   
  47.             {   
  48.   
  49.                 sqlConn.Open();//打开数据库连接   
  50.   
  51.                 MessageBox.Show("打开数据库连接成功!","提示",MessageBoxButtons.OK,MessageBoxIcon.Information);   
  52.   
  53.             }   
  54.   
  55.             catch(Exception ex)   
  56.   
  57.             {   
  58.   
  59.                 MessageBox.Show(ex.Message);//打开数据库连接异常处理   
  60.   
  61.             }   
  62.   
  63.             finally  
  64.   
  65.             {   
  66.   
  67.                 sqlConn.Close();//关闭数据库连接   
  68.   
  69.                 MessageBox.Show("关闭数据库连接成功!""提示", MessageBoxButtons.OK, MessageBoxIcon.Information);   
  70.   
  71.             }   
  72.   
  73.         }   
  74.   
  75.     }   
  76.   
  77. }  
上一篇:ADO.NET中的.NET..    下一篇:C#对ADO.NET数据..

相关主题:

网友评论