c#动态生成配方中,怎么将以上读取到的数据代入配方
时间: 2024-02-17 07:00:03 浏览: 20
如果你想要将读取到的数据代入到配方中,可以使用字符串格式化来实现。假设你的配方字符串如下:
```
string recipe = "制作 {0} 需要 {1} 克 {2} 和 {3} 克 {4},加入 {5} 克盐,煮沸 {6} 分钟即可。"; // 这里只是一个示例,你需要根据你的具体情况修改
```
你可以使用 `string.Format` 方法来将读取到的数据代入到配方中,示例代码如下:
```
using System;
using System.Data;
using System.Data.SqlClient;
class Program
{
static void Main(string[] args)
{
string connectionString = "Data Source=<server_name>;Initial Catalog=Adv;Integrated Security=True"; // 请替换为你的数据库连接字符串
string query = "SELECT * FROM Recipe WHERE RecipeID = @RecipeID"; // 查询语句
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@RecipeID", 1); // 请替换为你要查询的配方 ID
connection.Open();
SqlDataReader reader = command.ExecuteReader();
if (reader.Read())
{
string recipe = "制作 {0} 需要 {1} 克 {2} 和 {3} 克 {4},加入 {5} 克盐,煮沸 {6} 分钟即可。";
string name = reader["Name"].ToString();
int amount1 = (int)reader["Amount1"];
string ingredient1 = reader["Ingredient1"].ToString();
int amount2 = (int)reader["Amount2"];
string ingredient2 = reader["Ingredient2"].ToString();
int salt = (int)reader["Salt"];
int time = (int)reader["Time"];
string result = string.Format(recipe, name, amount1, ingredient1, amount2, ingredient2, salt, time);
Console.WriteLine(result);
}
reader.Close();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
```
在这个示例中,我们通过读取数据库中的 `Recipe` 表来获取配方信息,并将数据代入到配方字符串中。最终输出的结果会包含从数据库中读取到的数据。