一,执行返回唯一值得查询 /// <summary> /// 执行返回唯一值得查询 /// </summary> void CreateCommandScalar() { string strConn = "Data Source=localhost;Initial Catalog=Table;Integrated Security=SSPI;"; SqlConnection conn = new SqlConnection(strConn); SqlCommand comm = conn.CreateCommand(); comm.CommandType = CommandType.Text; comm.CommandText = "SELECT COUNT(*) FROM T_USER A"; conn.Open(); //返回结果集中第一行第一列 int iNum = (int)comm.ExecuteScalar(); conn.Close(); MessageBox.Show("num : " + iNum.ToString()); } 二,执行没有返回值得调用 /// <summary> /// 执行没有返回值得调用 /// </summary> void CreateCommandNonQuery() { string strConn = "Data Source=localhost;Initial Catalog=Table;Integrated Security=SSPI;"; SqlConnection conn = new SqlConnection(strConn); SqlCommand comm = conn.CreateCommand(); comm.CommandType = CommandType.Text; comm.CommandText = "SELECT COUNT(*) FROM T_USER A"; conn.Open(); SqlDataReader reader = comm.ExecuteReader(); reader.Read(); if (!reader.IsDBNull(0)) { object[] objs = new object[1]; reader.GetValues(objs); MessageBox.Show("SqlDataReader : " + objs[0]); } conn.Close(); /*循环读取数据 while (reader.Read()) { } */ } 三, 多个数据集的调用 /// <summary> /// 多个数据集的调用 /// </summary> void CreateMultiDataset() { string strConn = "Data Source=localhost;Initial Catalog=Table;Integrated Security=SSPI;"; SqlConnection conn = new SqlConnection(strConn); SqlCommand comm = conn.CreateCommand(); comm.CommandType = CommandType.Text; comm.CommandText = "SELECT A.SUMMARY FROM T_USER A WHERE A.SUMMARY = N'12345';" + "SELECT COUNT(*) FROM T_USER A"; conn.Open(); SqlDataReader reader = comm.ExecuteReader(); while (reader.Read()) { if (!reader.IsDBNull(0)) { object[] objs = new object[1]; reader.GetValues(objs); MessageBox.Show("CreateMultiDataset1 : " + objs[0]); } } reader.NextResult(); while (reader.Read()) { if (!reader.IsDBNull(0)) { object[] objs = new object[1]; reader.GetValues(objs); MessageBox.Show("CreateMultiDataset2 : " + objs[0]); } } conn.Close(); }