【问题标题】:SQL Queries + DataTable + GridViewSQL 查询 + 数据表 + GridView
【发布时间】:2014-07-25 21:55:56
【问题描述】:

我需要从 SQL 数据库中读取数据并在表中创建以下结果:

DATABASE
=========
Server, Site Name, Status
001, Site 1, Down
002, Site 1, Up
003, Site 2, Up
004, Site 2, Down
001, Site 3, Up
005, Site 4, Down
  • 站点 1:它存在于 2 个服务器(001、002)中
  • 站点 2:它存在于 2 个服务器(003、004)中
  • 站点 3:它仅存在于 1 个服务器 (001) 中
  • 站点 4:它仅存在于 1 个服务器 (005)

结果:

@@@@@@@@@@@@@@@@@@@@@@@

站点名称 1 = 1 长列

@@@@@@@@@@@@@@@@@@@@@@@

服务器 1 = 第 1 列 ||服务器 2 = 第 2 列

@@@@@@@@@@@@@@@@@@@@@@@

站点名称 2 = 1 长列

@@@@@@@@@@@@@@@@@@@@@@@

服务器 1 = 第 1 列 ||服务器 2 = 第 2 列

@@@@@@@@@@@@@@@@@@@@@@@

这是我的 C# 代码

SqlConnection myConnection = new SqlConnection("my connection");
string SqlCon = "SELECT distinct(Site_Name) as SN FROM TABLE;";
using (myConnection)
{
    myConnection.Open();
    SqlDataAdapter da1 = new SqlDataAdapter(SqlCon, myConnection);
    DataTable dt = new DataTable();
    da1.Fill(dt);

    foreach (DataRow dr in dt.Rows) //IS THIS CORRECT?
    {
       string SqlCon2 = "SELECT * FROM LIVEWEBSITES WHERE Site_Name='" + dr["SN"].ToString() + "';";

       //Crete the table and populate it here

       if Status==Down then bgcolor of the cell = RED
       else bgcolor = GREEN

    }             

    MyGridView.DataSource = dt;
    MyGridView.DataBind();
}

第一个 SQL 查询是只选择有区别的站点

然后使用该信息我执行另一个 SQL 查询以选择所有信息并相应地填充表

我该怎么做?

【问题讨论】:

  • 也许 LINQ 会更好地满足我的需求?如果有,怎么做?

标签: c# sql gridview datatable


【解决方案1】:

您是否考虑过使用DataContextDbContext。您基本上将数据库映射到您的代码。然后,您可以利用 LINQ。

例如,如果您有一个 Student 表和 StudentInfo 表,您可以这样做:

public class MyContext : DataContext
{
    public Table<Student> Students { get { return GetTable<Student>(); } }
    public Table<StudentInfo> StudentInfo { get { return GetTable<StudentInfo>(); } }
    public MyContext(string ConnString) : base(ConnString) {}
}

[Table(Name = "dbo.Students")]
public class Student
{
    [Column(IsPrimary = true, Name = "StudentId", IsDbGenerated = true, DbType = "int Not Null IDENTITY")]
    public int StudentId { get; set; }
    [Column(Name = "Name")]
    public string Name { get; set; }
}

[Table(Name = "dbo.StudentInfo")]
public class StudentInfo
{
    [Column(IsPrimary = true, Name = "StudentInfoId", IsDbGenerated = true, DbType = "int Not Null IDENTITY")]
    public int StudentInfoId { get; set; }
    [Column(Name = "StudentId")]
    public int StudentId { get; set; }  // FK
    [Column(Name = "Address")]
    public string Address{ get; set; }
}

// a method somewhere
public void StudentLookup(string name)
{
    var MyContext context = new MyContext(connString);
    var student = context.Students.Single(x => x.Name == name)
    var StudentInfo = context.StudentInfo.Where(x => x.StudentId == student.StudentId);
}

这是一种选择,但我建议将实体框架与代码优先迁移一起使用

【讨论】:

    猜你喜欢
    • 2020-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-07
    • 2017-08-30
    • 2013-01-26
    • 1970-01-01
    • 2019-07-22
    相关资源
    最近更新 更多