ADO.NET查询和检索数据

一、建立数据库School,数据表名为Teacher。

二、创建Windows应用程序,在窗体中添加一个查询按钮,程序运行时,单击查询按钮,将检索到的数据显示在消息框中。在“查询”按钮的Click事件中添加代码如下:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace School
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void button1_Click(object sender, EventArgs e)
        {
            string strcon=@"data source=.\sqlexpress;initial catalog=School;uid=sa;pwd=123456";
            SqlConnection con = new SqlConnection(strcon);
            string sql = "select count(*) from Teacher";
            SqlCommand comm = new SqlCommand(sql,con);
            try
            {
                con.Open();
                int number = (int)comm.ExecuteScalar();
                string message = string.Format("Teacher表中共有{0}条记录",number);
                MessageBox.Show(message,"查询结果",MessageBoxButtons.OKCancel,MessageBoxIcon.Information);

            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                con.Close();
            }
           
        }
    }
}

 

在本代码中,查询Teacher表中记录的数量,在消息框中显示查询结果。
在本代码中,采用了try...catch...finally结构的异常处理机制,通常在数据库操作时都要引入异常处理。打开数据库连接代码要放在异常结构处理的正常处理块中,在finally语句块中写入关闭数据库连接的方法,表示无论是出现异常,都要关闭数据库连接。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值