SQL命令无法打印到标签

时间:2016-02-20 13:21:21

标签: c# sql asp.net sql-server

我试图将SQL命令输出到标签。我正在连接数据库,但输出不正确。

这是我的代码

SqlCommand com = new SqlCommand("Select SUM(IncCost) FROM Incomings WHERE CONVERT(DATETIME, IncDate, 103) <= GETDATE()");

totalInc.Text = com.ToString();

loadDatabase(com);

我试图将IncCost中的所有值添加到今天或更早的日期和之后的日期,直到那天才会添加。

我目前为标签totalInc获取的输出是:

System.Data.SqlClient.SqlCommand

(我使用的日期是DD / MM / YYYY,我想我正确地将它转换为日期/时间。)提前干杯以获得任何帮助,我确定它和&#39; #39;一个简单的解决方案!

3 个答案:

答案 0 :(得分:1)

首先需要对数据库进行连接,然后您可以创建命令并执行以从数据库中获取数据。

尝试这样的事情:

// define connection string and query to execute
string connectionString = "server=.;database=YourDB;Integrated Security=SSPI;";
string query = "Select SUM(IncCost) FROM Incomings WHERE CONVERT(DATETIME, IncDate, 103) <= GETDATE();";

// set up connection to database and query command object
using (SqlConnection conn = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, conn))
{
    // open connection, execute command, close connection
    conn.Open();

    // you can use ExecuteScalar, since your query returns only a single value
    int sumOfIncCost = (int)cmd.ExecuteScalar();

    conn.Close();

    // set label text
    totalInc.Text = sumOfIncCost.ToString();
}

答案 1 :(得分:0)

如果您希望 SQL查询位于标签中,请将label.Text设置为com.CommandText

如果您希望执行SQL查询的结果在您的标签中,请执行该标记并将label.Text设置为结果,例如label.Text = ((int)com.ExecuteScalar()).ToString()

答案 2 :(得分:0)

只需要3个步骤

  1. 连接

    using (SqlConnection cnn = New SqlConnection(@"yourconnectionString")
    {
        cnn.Open();    
    }
    
  2. Sql命令

    using (SqlConnection cnn = new SqlConnection(@"yourconnectionString")
    {
       cnn.Open();    
    
       using (SqlCommand cmd = new SqlCommand("Select SUM(IncCost) FROM Incomings WHERE CONVERT(DATETIME, IncDate, 103) <= GETDATE()", cnn))
       {
       }
    }
    
  3. 阅读价值

    using (SqlConnection cnn = new SqlConnection(@"yourconnectionString")
    {
       cnn.Open();    
    
       using (SqlCommand cmd = new SqlCommand("Select SUM(IncCost) FROM Incomings WHERE CONVERT(DATETIME, IncDate, 103) <= GETDATE()", cnn))
       {
           var oValue = cmd.ExecuteScalar();
           //Now the value is ready to print
           totalInc.Text = ((decimal)oValue).toString("0.00");
       }
    }