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那个的查询的结果,这个查询本来就不返回结果

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?