2011-09-04 73 views
0

我已经创建了一个数据源来连接SQL Server数据库。当我使用GridView连接它时它工作正常。我需要阅读某个项目(比如FirstName)并将该值存储到一个变量中。使用数据源读取SQL Server数据库

如何使用此数据源?你可以给我这些陈述吗?

感谢

回答

3

SqlDataSource旨在作为顾名思义 - 用于数据绑定的数据源。它是而不是一种从数据库表中获取单个值的方法。

如果您需要读取一个值,你应该使用ADO.NET直 - SqlConnectionSqlCommand - 阅读该值 - 是这样的:

string sqlStmt = "SELECT FirstName FROM dbo.YourTable WHERE ID = @ID"; 

using(SqlConnection conn = new SqlConnection(your-connection-string-here-)) 
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn)) 
{ 
    cmd.Parameters.Add("@ID", SqlDbType.Int).Value = 4044; 

    conn.Open(); 
    string firstName = cmd.ExecuteScalar().ToString(); 
    conn.Close(); 
} 

,如果你想读的ExecuteScalar调用工作只单行,单列值 - 就像这里一样。否则,您需要使用SqlDataReader,或使用DataTableSqlDataAdapter填充该数据表(如果您有多行)。

更新:,如果你想使用一个SqlDataAdapter代替 - 这样做:

public DataTable LoadData() 
{ 
    DataTable result = new DataTable(); 

    string sqlStmt = "SELECT ID, FirstName, LastName, Country " + 
        "FROM dbo.YourTable"; 

    using(SqlConnection conn = new SqlConnection(your-connection-string-here-)) 
    using(SqlCommand cmd = new SqlCommand(sqlStmt, conn)) 
    { 
     SqlDataAdapter dap = new SqlDataAdapter(cmd); 
     dap.Fill(result); 
    } 

    return result; 
} 

当你调用这个方法,你会得到一个DataTable包含您所定义的列的SQL语句以及数据库表中的所有行。现在

DataTable myData = LoadData(); 

,你可以遍历行,并获得FirstName值的每一行:

foreach(DataRow row in myData.Rows) 
{ 
    string firstName = row["FirstName"].ToString(); 
    // do whatever you need to do with the first name 
} 
+0

是像ds.Tables [ “表名”]行[ROWNUMBER] [ “的ColumnName” ]可能吗?即使这不起作用,但有人推荐给我。 –

+0

@furqan sehgal:如果你使用'SqlDataAdapter'并填充'DataTable' - 是的!用'SqlDataSource' - 不行。 –

+0

请指教如何添加sqlDataAdapter和Datatable以及如何绑定它们。有没有像WinForms中的绑定源。也请说明我需要做我的必要的操作。 –