c# - 如何从函数中的选择查询返回 int 值?

标签 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;
}

最佳答案

您正在搜索返回第一个值的 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;
}

关于c# - 如何从函数中的选择查询返回 int 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9923623/

相关文章:

c# - Azure 存储 - 处理 URL 中的双斜杠

sql-server - 具有插入和删除功能的通用表表达式

c# - 我如何知道 SQL Server 客户端连接池的实际利用率?

sql - SQL 中的 IsDate 函数将无效日期评估为有效日期

c# - 是否可以增加 C# AOT 内联方法长度限制?

c# - 更新经典桌面应用的 Application Insights 检测 key 的最佳实践

c# - .NET - 如何创建一个类,以便只有一个其他特定类可以实例化它?

sql-server - SQL复制: Access snapshot folder is denied (SQL Server 2008)

SQL CASE 与乘法

c# - MVC Action 属性测试