日期:2014-05-19  浏览次数:20836 次

怎么获得sql查询中的数据?
数据库连接部分我会写,如下面,可是   怎么获得查询结果中的列的内容呢?比如“省份”中的内容?
  string   strconn   =   System.Configuration.ConfigurationManager.ConnectionStrings[ "LocalSqlServer "].ToString();
                SqlConnection   con   =   new   SqlConnection(strconn);
                string   cmdstring   =   "SELECT     id,名称,   省份   FROM     hotel   WHERE   id   =   ' "   +   id   +   " ' ";
          SqlCommand   cmd   =   new   SqlCommand(cmdstring,   con);
                con.Open();

------解决方案--------------------
dataReader
dataSet
………………
请看msdn
------解决方案--------------------
去看看SqlDataAdapter、SqlDataReader类。


--------------------------------------------
析软网
http://www.parsesoft.net
致力于 DocBook 的应用,专注于开源软件的解析、手册/指南、以及应用文章、书籍的发布
------解决方案--------------------
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
static void Main()
{
string connectionString = GetConnectionString();
string queryString =
"SELECT CategoryID, CategoryName FROM dbo.Categories; ";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command = connection.CreateCommand();
command.CommandText = queryString;

try
{
connection.Open();

SqlDataReader reader = command.ExecuteReader();

while (reader.Read())
{
Console.WriteLine( "\t{0}\t{1} ",
reader[0], reader[1]);
}
reader.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}

static private string GetConnectionString()
{
// To avoid storing the connection string in your code,
// you can retrieve it from a configuration file.
return "Data Source=(local);Initial Catalog=Northwind; "
+ "Integrated Security=SSPI ";
}
}