如何从SqlDataReader返回单个值? [英] How can I return a single value from an SqlDataReader?
问题描述
我忘了在单层应用程序中返回值.
I forget to return value in single tier application.
public int Studentid()
{
try
{
SqlConnection con = new SqlConnection(connectionStr);
SqlCommand cmd = new SqlCommand("SELECT s_id FROM student where name = + ('" + Request.QueryString.ToString() + "')", con);
con.Open();
SqlDataReader dr = null;
con.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
//Want help hear how I return value
}
con.Close();
}
catch (Exception ex)
{
throw ex;
}
}
推荐答案
这是实现您所追求的目标的方法的版本.
Here is a version of your method that achieves what you're after.
public int GetStudentId()
{
var sql = string.Format("SELECT s_id FROM student where name = '{0}'", Request.QueryString);
using (var con = new SqlConnection(connectionStr))
using (var cmd = new SqlCommand(sql, con))
{
con.Open();
var dr = cmd.ExecuteReader();
return dr.Read() ? return dr.GetInt32(0) : -1;
}
}
当您除了重新抛出(异常抛出)(实际上您通过使用 throw ex;
而不是只需 throw;
.另外,C# using
语句可帮助您以更少的代码行为您清理资源.
There's no need to use try/catch when you don't do anything with the exception except re-throw (and in fact you were losing the original stack trace by using throw ex;
instead of just throw;
. Also, the C# using
statement takes care of cleaning up your resources for you in fewer lines of code.
重要
IMPORTANT
像这样直接将查询字符串传递到SQL,意味着任何人都可以在您的数据库中执行随机SQL,从而有可能删除所有内容(或更糟的是删除所有内容).阅读 SQL注入.
Passing the query string directly into SQL like that means that anyone can execute random SQL into your database, potentially deleting everything (or worse). Read up on SQL Injection.
这篇关于如何从SqlDataReader返回单个值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!