gpt4 book ai didi

c# - c# 中的 AVG 查询

转载 作者:太空宇宙 更新时间:2023-11-03 21:03:14 25 4
gpt4 key购买 nike

早上好,我正在开发一个代码,可以让我在 sql 中退出数据库,即某个列的 AVG。问题是我不明白,我认为问题出在查询上,但我不知道如何解决。我需要帮助,谢谢。

代码如下:

String connectionString =
"Data Source=localhost;" +
"Initial Catalog=DB_SACC;" +
"User id=sa;" +
"Password=1234;";

SqlConnection connection = new SqlConnection(connectionString);

SqlCommand cmd = new SqlCommand();

string textt = " USE [DB_SACC] SELECT AVG (Total_Divida) FROM t_pagamentos";

cmd.CommandText = textt;

connection.Open();

cmd.Connection = connection;

cmd.CommandType = CommandType.Text;

cmd.ExecuteNonQuery();

if (textt == null)
{
MessageBox.Show("nothing");
}
else
{
TextBox3.Text = textt;
}

最佳答案

  • 如果您从数据库请求单个值,请使用 ExecuteScalar - ExecuteNonQuery 仅返回更新/插入语句中使用的受影响行数
  • USE [DB_SACC] 在您的查询中不是必需的,因为您定义了 "Initial Catalog=DB_SACC;"
  • 添加使用以避免打开连接

代码:

string connectionString =  "Data Source=localhost;Initial Catalog=DB_SACC;User id=sa;Password=1234;";

using (SqlConnection connection = new SqlConnection(connectionString))
{
string textt = "SELECT AVG (Total_Divida) FROM t_pagamentos";
using (SqlCommand cmd = new SqlCommand(textt, connection))
{
connection.Open();
var result = cmd.ExecuteScalar(); //write the result into a variable

if (result == null)
{
MessageBox.Show("nothing");
}
else
{
TextBox3.Text = result.ToString();
}
}
}

关于c# - c# 中的 AVG 查询,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43249940/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com