在C#中怎样把数据库中的数据添加到DataTable中

2024-11-15 14:34:01
推荐回答(4个)
回答1:

// 从数据库中查询数据,返回DataTable
DataTable Query(OleDbConnection conn, string sql)
{
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, conn);

DataSet ds = new DataSet();
try
{
adapter.Fill(ds, "factors");
}
catch (Exception ex)
{
_log.Error("GetFactorsInfo() fail: ", ex);
}

return ds.Tables[0];
}

// 将DataTable中的数据显示到DataGridView中
void ShowData(DataTable dt, DataGridview dgv)
{
dgv.Columns.Clear();
if (dt != null)
{
dgv.AutoGenerateColumns = true;
dgv.DataSource = dt;
}
}

回答2:

SqlConnection con=new SqlConnection("Server=.;database=Test;uid=sa;pwd=sa");
SqlDataAdapter sda=new SqlDataAdapter("Select * from News",con);
Datatable dt=new DataTable();
sda.Fill(dt);
con.Close();

dt为所要的

回答3:

public static DataTable ExecuteTable(CommandType cmdType, string cmdText, params SqlParameter[] pn)
{
SqlConnection con = new SqlConnection(connectionstring);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = cmdType;
cmd.CommandText = cmdText;
if (pn != null)
{
foreach (SqlParameter p in pn)
{
cmd.Parameters.Add(p);
}
}
SqlDataAdapter sda = new SqlDataAdapter();
sda.SelectCommand = cmd;
DataTable dt=new DataTable();
sda.Fill(ds);
return dt;
}
DataGridView1.DataSource=dt;
DataGridView1.DataBind();

回答4:

dataset.tables[]