这是其中一个按钮的示例。 [我能够从数据库中检索艺术家,名称和流派,但不能从价格中检索。代码应该是什么来检索价格?我已经将数据类型数据类型设置为数据库中的varchar(50)
,然后尝试使用小数和int,并且不使用它们
protected void btnSong6_Click(object sender, EventArgs e)
{
string Name = "In the end";
Product Music = new Product();
string constr = ConfigurationManager.ConnectionStrings["RegisterConnectionString"].ConnectionString;
SqlConnection con = new SqlConnection(constr);
con.Open();
string SelectCommand = "select Genre,Name,Artist, Price from Music WHERE name = '" + Name + "' ";
SqlCommand cmd = new SqlCommand(SelectCommand, con);
SqlDataReader read = cmd.ExecuteReader();
read.Read();
Music.Artist = read["artist"].ToString();
Music.Name = read["name"].ToString();
Music.Genre = read["genre"].ToString();
Music.Price= read["price"].ToString();
//ADD PRICE!!
listMusic.Items.Add(Music.Genre + " : " + Music.Artist + " - " + Music.Name);
}
答案 0 :(得分:1)
您的代码看起来不错,但您并没有使用“价格”。不完全确定你想用'价格做什么,也许把它添加到'listMusic'?
如果'Music.Price'是小数,则需要转换它:
Music.Price = Convert.ToDecimal(read["price"]);
然后将其添加到'listMusic':
listMusic.Items.Add(Music.Genre + " : " + Music.Artist + " - " + Music.Name + " $" + Music.Price);
您还应该考虑将数据库'price'列更改为Decimal。上面的代码应该以任何一种方式工作。
要在检索列值时减少所需的类型转换量,请查看this文章。 DataReader提供了一系列方法,允许您访问其本机数据类型中的列值。
类似的东西:
using (SqlConnection con = new SqlConnection(constr))
{
string SelectCommand = "select Genre,Name,Artist, Price from Music WHERE Name = '" + Name + "' ";
SqlCommand cmd = new SqlCommand(SelectCommand, con);
con.Open();
SqlDataReader read = cmd.ExecuteReader();
if (read.HasRows)
{
while (read.Read())
{
Music.Genre = read.GetString(0);
Music.Name = read.GetString(1);
Music.Artist = read.GetString(2);
Music.Price = read.GetDecimal(3);
listMusic.Items.Add(Music.Genre + " : " + Music.Artist + " - " + Music.Name + " $" + Music.Price);
}
}
}