Simple SQL select in C#?

后端 未结 5 704
春和景丽
春和景丽 2020-12-09 11:28

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 (a

相关标签:
5条回答
  • 2020-12-09 11:47

    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);
            }
     }
    
    0 讨论(0)
  • 2020-12-09 11:57

    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();
    }
    
    0 讨论(0)
  • 2020-12-09 12:01

    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.

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

    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.

    0 讨论(0)
  • 2020-12-09 12:04

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

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

    0 讨论(0)
  • 2020-12-09 12:05

    You are probably looking for SqlCommand and SqlDataReader

    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();
    }
    
    0 讨论(0)
提交回复
热议问题