cmd.ExecuteScalar() 返回空值时发生错误

本文介绍了解决cmd.ExecuteScalar()返回空值时发生的错误的方法。提供了两种实用的解决方案:一是通过判断返回值是否为null;二是通过查询记录数来判断是否存在数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

今天做作业运行时cmd.ExecuteScalar() 返回空值时发生错误了,然后我在网上找一下,发现了以下解决方法很有效果。

cmd.ExecuteScalar() 返回空值时发生错误的解决方法如下:


//---方法1 cmd.ExecuteScalar() != null
string strSql = "Select sName FROM tbD Where sName='aaa'";
SqlCommand cmd = new SqlCommand(strSql, myConn);
if (cmd.ExecuteScalar() != null)
{
      return true;
}
else
{
      return false;
}
cmd.Connection.Close();
myConn.Close();

 

 

//---方法2
string strSql = "Select count(*) FROM tbD Where sName='aaa'";
SqlCommand cmd = new SqlCommand(strSql, myConn);
int i = (int)cmd.ExecuteScalar();
cmd.Connection.Close();
myConn.Close();
if (i == 0)
{
      return true;
}
else
{
      return false;
}

//也可以用

 

 

嘿嘿,今天又解决了一个问题,很开心哦!

在最近做项目的过程中,我发现编程变得越来越有意思了。加油加油,努力!

using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Data.SqlClient; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace _2 { public partial class KnowledgeTree : Form { private string connectionString = "Data Source=localhost;Initial Catalog=pointnote;Integrated Security=True;"; // 声明控件变量 private SplitContainer mainSplitContainer; private TreeView treeView; private TextBox txtName1; private TextBox txtSubject1; private RichTextBox txtContent1; public KnowledgeTree() { InitializeComponent(); InitializeUI(); // 添加初始化调用 LoadKnowledgeTree(); // 添加树加载 } // 初始化界面控件 private void InitializeUI() { { // 主分割容器 mainSplitContainer = new SplitContainer { Dock = DockStyle.Fill, SplitterDistance = 300 }; this.Controls.Add(mainSplitContainer); // 树视图 treeView = new TreeView { Dock = DockStyle.Fill, ImageList = CreateImageList(), ShowNodeToolTips = true }; mainSplitContainer.Panel1.Controls.Add(treeView); // 详情面板 Panel detailPanel = new Panel { Dock = DockStyle.Fill }; mainSplitContainer.Panel2.Controls.Add(detailPanel); // 详情控件 txtName1 = new TextBox { Location = new Point(10, 30), Width = 200 }; txtSubject1 = new TextBox { Location = new Point(10, 70), Width = 200 }; txtContent1 = new RichTextBox { Location = new Point(10, 110), Size = new Size(400, 200) }; btnSave = new Button { Text = "保存", Location = new Point(10, 320) }; btnSave.Click += SaveKnowledge; // 绑定保存事件 detailPanel.Controls.AddRange(new Control[] { new Label { Text = "名称", Location = new Point(10, 10) }, txtName1, new Label { Text = "学科", Location = new Point(10, 50) }, txtSubject, new Label { Text = "内容", Location = new Point(10, 90) }, txtContent1, btnSave }); } } private ImageList CreateImageList() { ImageList images = new ImageList(); images.ColorDepth = ColorDepth.Depth32Bit; images.ImageSize = new Size(24, 24); // 使用系统图标(实际应用中应使用自定义图标) images.Images.Add(SystemIcons.Information); // 0: 普通节点 images.Images.Add(SystemIcons.Warning); // 1: 重要节点 images.Images.Add(SystemIcons.Question); // 2: 问题节点 return images; } // 加载知识点树状图 private void LoadKnowledgeTree() { TreeView treeView1 = this.Controls[0] is SplitContainer sc ? (TreeView)sc.Panel1.Controls[0] : null; if (treeview == null) return; treeview.Nodes.Clear(); treeview.BeginUpdate(); try { // 获取所有知识点 DataTable points = GetKnowledgePoints(); // 创建节点字典 var nodeDict = new Dictionary<int, TreeNode>(); // 第一遍:创建所有节点 foreach (DataRow row in points.Rows) { int pid = Convert.ToInt32(row["Pid"]); string nodeText = $"{row["Pname"]} ({row["Stype"]})"; TreeNode node = new TreeNode(nodeText) { Name = pid.ToString(), Tag = row, // 存储整行数据 ToolTipText = row["Content"].ToString(), ImageIndex = GetNodeIconIndex(row["Stype"].ToString()) }; nodeDict.Add(pid, node); } // 第二遍:建立父子关系 foreach (DataRow row in points.Rows) { int pid = Convert.ToInt32(row["Pid"]); object parentObj = row["ParentId"]; if (parentObj != DBNull.Value) { int parentId = Convert.ToInt32(parentObj); if (nodeDict.ContainsKey(parentId)) nodeDict[parentId].Nodes.Add(nodeDict[pid]); } else { treeview.Nodes.Add(nodeDict[pid]); } } // 展开所有节点 treeview.ExpandAll(); // 添加节点选择事件 treeview.AfterSelect += (s, e) => DisplayPointDetails(e.Node); } catch (Exception ex) { MessageBox.Show($"加载树失败: {ex.Message}"); } finally { treeview.EndUpdate(); } } private int GetNodeIconIndex(string v) { throw new NotImplementedException(); } // 从数据库获取知识点 private DataTable GetKnowledgePoints() { using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); string sql = @"SELECT p.Pid, p.Pname, p.Stype, p.Content, r.ParentId FROM pointnote p LEFT JOIN KnowledgeRelations r ON p.Pid = r.ChildId"; using (var da = new SqlDataAdapter(sql, conn)) { DataTable dt = new DataTable(); da.Fill(dt); return dt; } } } private void label1_Click(object sender, EventArgs e) { } // 显示选中知识点的详情 private void DisplayPointDetails(TreeNode node) { if (node?.Tag == null) return; DataRow row = (DataRow)node.Tag; txtName1.Text = row["Pname"].ToString(); txtSubject1.Text = row["Stype"].ToString(); txtContent1.Text = row["Content"].ToString(); } private void SaveKnowledge(object sender, EventArgs e) { if (string.IsNullOrWhiteSpace(txtName.Text)) { MessageBox.Show("知识点名称不能为"); return; } using (SqlConnection conn = new SqlConnection(connectionString)) { conn.Open(); string sql = @"INSERT INTO KnowledgeRelations (Pname, Stype, Content) VALUES (@name, @subject, @content); SELECT SCOPE_IDENTITY();"; using (var cmd = new SqlCommand(sql, conn)) { cmd.Parameters.AddWithValue("@name", txtName1.Text); cmd.Parameters.AddWithValue("@subject", txtSubject1.Text); cmd.Parameters.AddWithValue("@content", txtContent1.Text); try { int newId = Convert.ToInt32(cmd.ExecuteScalar()); MessageBox.Show($"保存成功! ID: {newId}"); LoadKnowledgeTree(); // 刷新树 } catch (Exception ex) { MessageBox.Show($"保存失败: {ex.Message}"); } } } } } } 错误:未将对象引用设置设置到对象的实例
07-05
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值