get data from db by id in csharp

You can use ADO.NET in C# to retrieve data from a database by ID. Here's an example:

main.cs
using System.Data.SqlClient; //Make sure to include the namespace for SQL Server

int id = 1; //Set the ID you want to retrieve data for

string connectionString = "Data Source=YourServerName;Initial Catalog=YourDatabaseName;Integrated Security=True"; //Replace with your connection string to the database

string sql = "SELECT * FROM YourTableName WHERE ID = @ID"; //Use parameterized query to prevent SQL injection attacks

using (SqlConnection connection = new SqlConnection(connectionString)) //Open connection to database
{
    connection.Open();

    using (SqlCommand command = new SqlCommand(sql, connection)) //Create command object with SQL query and connection
    {
        command.Parameters.AddWithValue("@ID", id); //Add parameter to command to set value of ID

        using (SqlDataReader reader = command.ExecuteReader()) //Create data reader to read data returned by query
        {
            if (reader.Read()) //Check if data was retrieved
            {
                //Access values retrieved from the database
                int retrievedId = reader.GetInt32(reader.GetOrdinal("ID"));
                string retrievedValue1 = reader.GetString(reader.GetOrdinal("Value1"));
                string retrievedValue2 = reader.GetString(reader.GetOrdinal("Value2"));
                //etc.
            }
            //Handle if ID was not found in database
            else
            {
                Console.WriteLine("ID not found in database");
            }
        }
    }
}
1505 chars
35 lines

In this example, replace YourServerName, YourDatabaseName, YourTableName with the appropriate values for your database. Also make sure to replace ID, Value1, Value2, etc. with the column names in your table.

gistlibby LogSnag