在C#中简单的SQL选择? [英] Simple SQL select in C#?
问题描述
在我的当前项目,得到一个单一值(从表列其中id = VAL)时,previous程序员经过使用数据行,数据表和sqldatadapter(当然的SqlConnection的)只是为了得到一个值。
On my current project, to get a single value (select column from table where id=val), the previous programmer goes through using a datarow, datatable and an sqldatadapter (and of course sqlconnection) just to get that one value.
有没有做一个简单的选择查询更简单的方法?在PHP中,我可以只使用的mysql_query
然后 mysql_result
和我完成了。
Is there an easier way to make a simple select query? In php, I can just use mysql_query
and then mysql_result
and I'm done.
这将是很好,如果我可能只是这样做:
It would be nice if I could just do:
SqlConnection conSql = new SqlConnection(ConnStr);
SomeSqlClass obj = new SomeSqlClass(sql_string, conSql);
conSql.Close();
return obj[0];
感谢您的任何提示。
Thanks for any tips.
推荐答案
您可以跳过的DataReader
和的DataAdapter
并调用的ExecuteScalar()
上的SQL命令。
You can skip the DataReader
and the DataAdapter
and just call ExecuteScalar()
on the sql command.
using (SqlConnection conn = new SqlConnection(connString))
{
SqlCommand cmd = new SqlCommand("SELECT * FROM whatever
WHERE id = 5", conn);
try
{
conn.Open();
newID = (int)cmd.ExecuteScalar();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
这篇关于在C#中简单的SQL选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!