学习笔记2019.3.9(sqlconnection和sqlcommand的应用)

主题:ADO.Net中SqlConnection、Sqlcommand的应用

知识点描述:SqlConnection的应用,创建SqlConnection conn=new SqlConnection();输入连接的数据源ConnectionString,测试连接成不成功。接着创建SqlConnection cmd=new SqlConnection( );再创建cmd.CommandText =“ ”;和cmd.CommandType =CommandType .Text;用带参数的的方法编写sql语句防止sql注入。(编写时需加上System.Data.SqlClient;)

思维导图:

                            

                  

 

自编范例:

  1. 测试连接例子(SqlConnection应用):点击连接按钮,如果成功连接则跳出“连接成功”,否则跳出“连接失败”,运行结果如下:

                                          

 

      2.以查询为例子(SqlCommand应用):输入学号点击查询如果查到相应学号显示学生姓名,否则跳出“查无此人”,设置焦点在学号输入框,重新输入,运行结果如下:

                                        

 

                                         

 

                                         

程序代码如下:

                        

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


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

        private void Form1_Load(object sender, EventArgs e)
        {
            
        }

        private void ceshi_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data source=SQDOLEDB.1;server=(local);DataBase=EduBase;Integrated Security=SSPI");
            conn.Open();
            if (conn.State == ConnectionState.Open)
            {
                MessageBox.Show("连接成功");

            }
            else
            {
                MessageBox.Show("连接失败");
            }
        }

        private void Select_Click(object sender, EventArgs e)
        {
            SqlConnection conn = new SqlConnection("Data source=SQDOLEDB.1;server=(local);DataBase=EduBase;Integrated Security=SSPI");
            conn.Open();
            SqlCommand cmd = new SqlCommand("select*from tb_student where No=@No",conn);
            cmd.Parameters.Add(new SqlParameter("@No",SqlDbType.Char,20));
            cmd.Parameters["@No"].Value= textBox2.Text;
            SqlDataReader dr = cmd.ExecuteReader();
            if (dr.Read())
            {
                textBox1.Text = dr["Name"].ToString();
            }
            else
            {
                MessageBox.Show("查无此人");
                textBox1.Text = "";
                textBox2.Focus();
                textBox2.SelectAll();
            }
        }
    }
}


 

 

 

 

 

 

 

 

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值