我是C#的新手......努力学习它...我想知道如何根据datarow中的一个列值检索整个行数据。让我通过举例来说明一点..
MerchantNo TerminalNum CardType Date
110033445 770010449 Amex 5/09/2011
现在我想根据商家编号检索这一行,然后将其插入到sql表中。
我在想的是:
if(MerchantNo!="")
then retrieve the row
and insert data in sql table..
其实我正在处理导入excel文件。希望你明白我的问题
string Mno = "";
foreach (DataRow rowExcel in dtExcel.Rows)
{
foreach (DataColumn colExcel in dtExcel.Columns)
{
Mno = rowExcel[colExcel].ToString().Trim();
if (Mno != "")
{
string Mno1 = Mno.Substring(16, 10);
Mno =Mno1.ToString();
//Int32 MerchNo = Convert.ToInt32(Mno);
}
break;
}
if(Mno!="")// Mno contains the exact MerchantNo.
{
}
//break;
}
答案 0 :(得分:0)
//check if MerchantNo column is neither null nor empty
//r is an object of DataRow
if (Convert.IsDBNull(r["MerchantNo"]) == false && r["MerchantNo"].ToString().Trim() != String.Empty)
{
//Build an Sql Insert statement based on the data or row
string strSql = String.Format("INSERT INTO SOMETABLE(X,Y,Z) VALUES('{0}', '{1}', '{2}');", r["colName1"], r["colName2"], r["colName3"]);
}
答案 1 :(得分:0)
与Waqas所说的类似,但附加了foreach循环以澄清:
int MerchNo = 0;
foreach (DataRow r in dtExcel.Rows)
{
if (!String.IsNullOrEmpty(r["MerchantNo"].ToString().Trim()) &&
Int32.TryParse(r["MerchantNo"].ToString().Trim(), out MerchNo))
{
string strSql = String.Format("INSERT INTO SomeTable(MerchantNo, TerminalNum, CardType, Date) VALUES('{0}', '{1}', '{2}', '{3}');", r["MerchantNo"], r["TerminalNum"], r["CardType"], r["Date"]);
SqlCommand scInsertCommand = new SqlCommand(strSql);
//do transacion and connection assignment, and error handling
scInsertCommand.ExecuteNonQuery();
}
}