C#学生档案查询
安静点DGC 人气:0using 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 参数查询 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private SqlDataAdapter sqlDataAdapter; private DataSet dataSet; private void Form1_Load(object sender, EventArgs e) { // TODO: 这行代码将数据加载到表“xsglDataSet.student”中。您可以根据需要移动或删除它。 // this.studentTableAdapter.Fill(this.xsglDataSet.student); //Sqlconnection就是建立到sqlserver数据库的打开的连接 SqlConnection myConnection = new SqlConnection(); myConnection.ConnectionString = "server=localhost;uid=sa;pwd=root;database=xsgl"; // SqlCommand对象用来对SQL Server数据库执行操作命令。 SqlCommand sqlCommand = new SqlCommand(); sqlCommand.Connection = myConnection; sqlCommand.CommandType = CommandType.Text; //模糊查询 sqlCommand.CommandText = "select * from student where studID like @studID and studName like @studName and studSex like @studSex"; //comm.Parameters.Add()添加参数到参数集,add里面的第一个参数是要添加的参数名,第二个参数是参数的数据类型,第三个是长度 ,Parameters的作用就是把存储过程执行结束后得到的参数传到程序里 sqlCommand.Parameters.Add("@studID",System.Data.SqlDbType.VarChar,10,"studID"); sqlCommand.Parameters.Add("@studName", System.Data.SqlDbType.VarChar, 10, "studName"); sqlCommand.Parameters.Add("@studSex", System.Data.SqlDbType.VarChar, 2, "studSex"); //下面的三个是赋值 sqlCommand.Parameters["@studID"].Value = "%"; sqlCommand.Parameters["@studName"].Value = "%"; sqlCommand.Parameters["@studSex"].Value = "%"; sqlDataAdapter = new SqlDataAdapter(); dataSet = new DataSet(); sqlDataAdapter.SelectCommand = sqlCommand; sqlDataAdapter.Fill(dataSet,"student"); dataGridView1.DataSource = dataSet; dataGridView1.DataMember = "student"; } private void button1_Click(object sender, EventArgs e) { try { if (textBox1.Text == "") {//如果没有输入id sqlDataAdapter.SelectCommand.Parameters["@studID"].Value = "%"; } else { sqlDataAdapter.SelectCommand.Parameters["@studID"].Value = textBox1.Text; } if (textBox2.Text == "") {//如果没有输入姓名 sqlDataAdapter.SelectCommand.Parameters["@studName"].Value = "%"; } else { sqlDataAdapter.SelectCommand.Parameters["@studName"].Value = textBox2.Text; } // if (comboBox1.SelectedIndex == 0) { sqlDataAdapter.SelectCommand.Parameters["@studSex"].Value = "%"; } else if (comboBox1.SelectedIndex == 1) { sqlDataAdapter.SelectCommand.Parameters["@studSex"].Value = "男"; } else { sqlDataAdapter.SelectCommand.Parameters["@studSex"].Value = "女"; } dataSet.Tables["student"].Clear(); sqlDataAdapter.Fill(dataSet,"student"); } catch (SqlException ee) { MessageBox.Show(ee.Message); } } } }
加载全部内容