主题: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;)
思维导图:
自编范例:
- 测试连接例子(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();
}
}
}
}