如何从函数中的select查询返回int值?

时间:2012-03-29 10:32:48

标签: c# sql-server

我需要从tbl_Ticket中检索Ticket_Id以传递到发送电子邮件功能的正文部分。 以下代码是否正确? 每次我得到Ticket_Id 1 ..

public int select_TicketId(){
    string strConn = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
    SqlConnection sqlCon = new SqlConnection(strConn);
    string getId = ("select Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
    sqlCon.Open();
    SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
    int i=cmd1.ExecuteNonQuery();
    return i;
}

4 个答案:

答案 0 :(得分:7)

您正在搜索ExecuteScalar,它返回第一个值。

using System.Configuration;
//
public int select_TicketId()
    {
       string strConn = ConfigurationManager.ConnectionStrings["conString"].ConnectionString.ToString();
    SqlConnection sqlCon = new SqlConnection(strConn);
       string getId = ("select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd='" + objNewTic_BAL.email + "' ");
       sqlCon.Open();
       SqlCommand cmd1 = new SqlCommand(getId, sqlCon);
       return Convert.ToInt32(cmd1.ExecuteScalar());
    }

还使用CommandProperties设置where语句以获得更好的安全性,如下所示:

public int select_TicketId()
{
    string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    int result = -1;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        SqlCommand command = new SqlCommand();
        command.Connection = connection;
        command.CommandType = CommandType.Text;
        command.CommandText = "select TOP 1 Ticket_Id from tbl_Ticket where Client_EmailAdd=@email";
        command.Parameters.Add("@email", SqlDbType.Text).Value = objNewTic_BAL.email;
        result = Convert.ToInt32(command.ExecuteScalar());
    }

    return result;
}

答案 1 :(得分:2)

答案 2 :(得分:2)

您正在呼叫ExecuteNonQuery。但这是一个查询。这应该有一些警告铃声:)

请尝试ExecuteScalar,然后将结果转换为int ...

return (int) cmd1.ExecuteScalar();

请注意,您还应该对命令和连接使用using语句,以便两者都正确关闭。

(之前我没有发现过这个)你应该肯定使用参数化SQL,而不是直接在SQL中包含一个值。否则,您可以SQL Injection attacks ...

开放

类似于:

private const string FetchTicketIdSql =
    "select Ticket_Id from tbl_Ticket where Client_EmailAdd = @Email";

public int FetchTicketId()
{
    // No need for ToString call...
    string connectionString =
        ConfigurationManager.ConnectionStrings["conString"].ConnectionString;
    using (SqlConnection connection = new SqlConnection(connectionString))
    {
        connection.Open();
        using (SqlCommand command = new SqlCommand(connection, FetchTicketIdSql))
        {
            command.Parameters.Add("@Email", SqlDbType.NVarChar).Value = 
                bjNewTic_BAL.email;
            return (int) command.ExecuteScalar();
        }
    }
}

如果没有一个结果,你应该考虑你想要发生什么......

答案 3 :(得分:0)

Hiral,

中的ExecuteNonQuery
int i=cmd1.ExecuteNonQuery();

将返回满足查询的记录数。在这种情况下,它是1(如果没有电子邮件则为0)

请尝试使用ExecuteReader。