C# 中的简单 SQL 选择?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1504895/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 18:14:08  来源:igfitidea点击:

Simple SQL select in C#?

c#asp.netsqlselect

提问by Chris

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.

在我当前的项目中,为了获得单个值(从表中选择 id=val 的列),以前的程序员使用数据行、数据表和 sqldatadapter(当然还有 sqlconnection)只是为了获得那个值。

Is there an easier way to make a simple select query? In php, I can just use mysql_queryand then mysql_resultand I'm done.

有没有更简单的方法来进行简单的选择查询?在 php 中,我可以只使用mysql_query然后mysql_result我就完成了。

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.

感谢您提供任何提示。

采纳答案by womp

You can skip the DataReaderand the DataAdapterand just call ExecuteScalar()on the sql command.

您可以跳过DataReaderDataAdapter并直接调用ExecuteScalar()sql 命令。

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);
        }
 }

回答by womp

Actually, there is a method SqlCommand.ExecuteScalar() that will simply return the first field from the first row of the returned results. Just for you.

实际上,有一个方法 SqlCommand.ExecuteScalar() 将简单地从返回结果的第一行返回第一个字段。只为你。

.NET Framework Class Library SqlCommand..::.ExecuteScalar Method

.NET Framework 类库 SqlCommand..::.ExecuteScalar 方法

Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

执行查询,返回查询返回的结果集中第一行的第一列。其他列或行将被忽略。

回答by Fahad

you can use SqlCommands executeScalar function. Please look at the following link

您可以使用 SqlCommands 的 executeScalar 函数。请看下面的链接

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx

回答by LukeH

You can do something very similar:

你可以做一些非常相似的事情:

using (SqlConnection conn = new SqlConnection(ConnStr))
using (SqlCommand cmd = new SqlCommand(sql_string, conn))
{
    conn.Open();
    return cmd.ExecuteScalar();
}

回答by Kristoffer Deinoff

You are probably looking for SqlCommandand SqlDataReader

您可能正在寻找SqlCommandSqlDataReader

Dictionary<int, string> users = new Dictionary<int, string>();
using(SqlConnection connection = new SqlConnection("Your connection string"))
{
    string query = "SELECT UserId, UserName FROM Users";
    SqlCommand command = new SqlCommand(query, connection);
    connection.Open();
    using (SqlDataReader reader = command.ExecuteReader())
    {
        while (reader.Read())
            users.Add(reader.GetInt32(0), reader.GetString(1));
    }
    connection.Close();
}