DataTable使用介绍:http://www.dotnetperls.com/datatable
SQL结果存到DataTable例子:http://stackoverflow.com/questions/6073382/read-sql-table-into-c-sharp-datatable
简要代码例子:
String conStr = @"server=stcvm-130;integrated security=true;database=RAADB"; SqlConnection con = new SqlConnection(conStr); SqlParameter catName = new SqlParameter("@CatName", "洗发水"); SqlCommand com = new SqlCommand(); com.CommandType = System.Data.CommandType.StoredProcedure; com.Connection = con; com.CommandText = "dbo.prc_GetCatPriceRange"; com.CommandTimeout = 90; com.Parameters.Add(catName); com.Parameters.Add("RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue; DataTable dataTable = new DataTable(); //The following two can also be replaced by 'SqlDataAdapter da = new SqlDataAdapter(com);' SqlDataAdapter da = new SqlDataAdapter(); da.SelectCommand = com; //This will query your database and return the result to your datatable da.Fill(dataTable); da.Dispose(); Console.WriteLine(dataTable.Rows.Count); foreach (DataRow dr in dataTable.Rows) Console.WriteLine(dr["minPrice"].ToString() + " " + dr[1].ToString());
这里可以看出,其关键点是SqlDataAdapter类。它的构造函数有很多,给定了关键参数即可。例如:
SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM table",constring);
这里在使用相关的代码的时候,遇到的一个问题是,执行完后有一个存储过程返回正常的结果,另外一个则返回0行,事实是它也应该有一行返回结果。尝试了很长时间,结果是using部分虽然没有编译出错,但是加上一些solution包后居然就好了。这个真是奇怪!
时间: 2024-10-10 04:35:36