ixmuzi 2020-05-15 12:24 采纳率: 0%
浏览 285
已采纳

C#,同时进行对数据库的添加和查询,数据添加进去了,但却不输出。

小萌新一个,求大神指点图片说明

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Security.Policy;

namespace ConsoleApp1
{
    class Program
    {
        static void Main(string[] args)
        {
            string lianjie = "server=.;database=T7;uid=sa;pwd=123456";
            SqlConnection a = new SqlConnection(lianjie);
            a.Open();
            if (a.State == ConnectionState.Open)
            {
                Console.WriteLine("序号\t游戏名称\t游戏类型\t\t游戏价格\t库存数量\t小计");
                string sql = "insert into games2(name,leixing,price,kucun,xiaoji) select'纪念碑谷','冒险解谜类手机游戏'" +
                    ",30,100,3000 union select'刺客信条','角色扮演类手机游戏',28,100,2800 union select'鳄鱼爱洗澡','休闲益智类手机游戏',6,100,600";
                SqlCommand b = new SqlCommand(sql, a);
                string sql2 = string.Format("select ID,name,leixing,price,kucun,xiaoji from games2");
                SqlCommand cmd = new SqlCommand(sql2, a);
                SqlDataReader r = b.ExecuteReader();
                while (r.Read())
                {
                    string id = r["ID"].ToString();
                    string name = r["name"].ToString();
                    string price = r["price"].ToString();
                    string kucun = r["kucun"].ToString();
                    string xiaoji = r["xiaoji"].ToString();
                    string leixing = r["leixing"].ToString();
                    Console.WriteLine("{0}\t《{1}》\t{2}\t{3}\t\t{4}\t\t{5}元", id, name, leixing, price, kucun, xiaoji);
                }
                r.Close();
                string sum = "select sum(price*kucun)from games2";
                SqlCommand c = new SqlCommand(sum, a);
                string sum1 = string.Format("{0}", c.ExecuteScalar());
                Console.WriteLine("库存游戏总金额:{0}元", sum1);
            }
            a.Close();
        }
    }
}
  • 写回答

1条回答 默认 最新

  • threenewbee 2020-05-15 13:53
    关注

    SqlCommand cmd = new SqlCommand(sql2, a);
    你构造了cmd,但是没有执行

    while (r.Read())
    这个输出的是insert那个的查询的结果,这个查询本来就不返回结果

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 maple软件,用solve求反函数出现rootof,怎么办?
  • ¥50 汇编语言除法溢出问题
  • ¥65 C++实现删除N个数据列表共有的元素
  • ¥15 Visual Studio问题
  • ¥15 state显示变量是字符串形式,但是仍然红色,无法引用,并显示类型不匹配
  • ¥20 求一个html代码,有偿
  • ¥100 关于使用MATLAB中copularnd函数的问题
  • ¥20 在虚拟机的pycharm上
  • ¥15 jupyterthemes 设置完毕后没有效果
  • ¥15 matlab图像高斯低通滤波