简体   繁体   English

如何将从数据表中获取的值存储到字符串中?

[英]How to store values got from datatable into a string?

I want to get Data table values and save them in a single string, where dt.rows.Count is more that 0. 我想获取数据表值并将它们保存在单个字符串中,其中dt.rows.Count 0。 在此处输入图片说明 I want get menu_name , menu_Quantity and store them into a single string where email=ariffnaj@gmail.com . 我想要得到menu_namemenu_Quantity并将它们存储到单个字符串中,其中email=ariffnaj@gmail.com If this is possible, can you show how to do it, this code only save into string at first column only 如果可能的话,您能演示如何执行此操作,此代码仅保存到字符串的第一列中

SqlConnection conn = new SqlConnection(ConfigurationManager.
                    ConnectionStrings["connectionString"].ConnectionString);
 string cartsql = "SELECT menu_name,menu_price,menu_quantity FROM cart where email=@email";
        SqlCommand cmd1 = new SqlCommand(cartsql, conn);
        cmd1.Parameters.AddWithValue("@email", Session["email"].ToString());
        SqlDataAdapter sda = new SqlDataAdapter(cmd1);
        DataTable dt = new DataTable();
        sda.Fill(dt);

        if (dt.Rows.Count > 0)
        {

            foreach (DataRow dtRow in dt.Rows)
            {
                string menuname = dtRow["menu_name"].ToString();
                string menuprice = dtRow["menu_price"].ToString();
                string menuquantity = dtRow["menu_quantity"].ToString();

            }

        }

My solution uses a SqlDataReader instead of SqlDataAdapter and DataTable . 我的解决方案使用SqlDataReader而不是SqlDataAdapterDataTable This is easier, if you only want to retrieve some values. 如果您只想检索一些值,这会更容易。 To build the string I use a StringBuilder , as it manages the resources better than string concatenation would. 为了构建字符串,我使用StringBuilder ,因为它比字符串连接更好地管理资源。

public string GetCartStringForEMail(string email)
{
    const string sql = "SELECT menu_name, menu_quantity FROM cart WHERE email=@email";

    string connectionString =
        ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
    using (var conn = new SqlConnection(connectionString))
    using (var cmd = new SqlCommand(sql, conn)) {
        var sb = new StringBuilder();
        cmd.Parameters.AddWithValue("@email", email);
        conn.Open();
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read()) {
            sb.Append(reader.GetString(0))
                .Append(", ")
                .AppendLine(reader.GetInt32(1).ToString());
        }
        return sb.ToString();
    }
}

Note that the using-statements automatically close the connection and release the resources. 请注意,使用语句会自动关闭连接并释放资源。

You can try coalesce function: 您可以尝试合并功能:

DECLARE @str nvarchar(MAX)
SELECT @str = (COALESCE(@str + ';', '') + CONCAT('Menu:', menu_name, ', Quantity:', menu_quantity)) 
FROM cart WHERE email=@email
SELECT @str as output

And then use: String str = cmd1.ExecuteScalar().ToString(); 然后使用: String str = cmd1.ExecuteScalar().ToString();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在C#中的字符串变量中存储数据表值 - how to store datatable values in string variable in c# 如何选择我从Excel获得的数据表中的数据表? - how to select datatable where datatable i got from excel? 从asp.net c#数据表访问单元格值到字符串,然后将其存储在会话中 - Accessing cell values from a an asp.net c# DataTable to a string to then store in the sessions Vars 如何将数据表中的值存储到数组中,并使用C#中的for循环从数组中检索每个值? - how to store values from datatable to array and retrive each values from array using for loop in c#? 如何用“#”分割字符串并将结果存储在数据表中 - How to split string by “#” and store result in a DataTable 将DataTable中的列值从byte []转换为String - Convert Column Values in a DataTable from byte[] to String 如何将数据表中的数据存储在数组中 - How to store the data from a datatable in an array 如何将 Select2 SelectList 中的值存储为字符串 - How to Store Values from Select2 SelectList as String 如何从字符串中分离整数值并将其存储到C#中的变量中 - how to seperate integer values from a string and store it into a variable in C# C# 如何将字符串值存储在循环输出的列表中 - C# How to store string values in a list outputted from a loop
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM