gpt4 book ai didi

c# - 向数据表添加列并添加数据

转载 作者:行者123 更新时间:2023-11-30 21:01:16 26 4
gpt4 key购买 nike

如何向数据表添加一列并根据条件向每一行添加数据。这就是我想要做的

conn = new OleDbConnection(@"Provider=Microsoft.Jet.OleDb.4.0;
Data Source =" + Server.MapPath("App_Data\\LR Product Database 2000.mdb"));
conn.Open();

Dictionary<string, string> items = new Dictionary<string, string>();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = "SELECT CODE, TITLE FROM tblProducts";

OleDbDataReader dbread = cmd.ExecuteReader();

while (dbread.Read())
{
productCode = (string)dbread["ProductCode"];
productTitle = items[productCode];
items.Add(productCode, productTitle);
}

sqlCon = new SqlConnection(ConfigurationManager.ConnectionStrings["LRVWebsite"].ToString());
sqlCon.Open();
dsSql = new DataSet();
SqlDataAdapter dba = new SqlDataAdapter(@"SELECT C.CustomerFirstName,C.CustomerLastName, C.CustomerCompany,C.CustomerPosition,C.CustomerCountry,C.CustomerProvince,C.CustomerContact,CP.ActionDate,CP.ProductCode,CP.CustomerEmail FROM tblCustomers C INNER JOIN tblCustomerProducts CP ON C.CustomerEmail = CP.CustomerEmail ORDER BY ActionDate DESC", connString);
dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];

foreach (DataRow dr in dt.Rows)
{
for (int i = 0; i < items.Count; i++)
{
if (dr["ProductCode"].ToString().Equals(productCode))
{
//here I want to add a new column and add data (productTitle) to the column


}
}

}

最佳答案

dba.Fill(dsSql,"Products");
DataTable dt = dsSql.Tables["Products"];

dt.Columns.Add("ColumnName", typeof(DataType));

if (dr["ProductCode"].ToString().Equals(productCode))
{
dr["ColumnName"] = value;
}

进一步我会扩展代码以避免 NullReferenceException

 if (!String.IsNullOrEmpty(dr["ProductCode"]) && dr["ProductCode"].ToString().Equals(productCode))
{
dr["ColumnName"] = value;
}

http://msdn.microsoft.com/en-us/library/hfx3s9wd.aspx

关于c# - 向数据表添加列并添加数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14336257/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com