Most Important concepts Flashcards

1
Q

How does Dataset and DataTable objects work together?

A

A Data set object is an in-memory cache of data, and it can contain server DataTable objects where each DataTable object represents a table of data in a databse with rows and columns. Dataset allows you to work with related tables, enforce constraints, and represent parent childe relationships between tables.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Explain the role of the DataAdapter class in ADO.NET. How does it interact with DataSet and DataTable?

A

Explanation: The DataAdapter is responsible for retrieving data from a data source (like SQL Server) and filling a DataSet or DataTable with that data. It can also be used to update the data source based on changes made to the DataSet. The Fill() method is used to load data, while the Update() method is used to push changes from the DataSet back to the database.

Example:
~~~
using System;
using System.Data;
using System.Data.SqlClient;

class Program
{
static void Main()
{
DataSet dataSet = new DataSet();

    using (SqlConnection connection = new SqlConnection("YourConnectionString"))
    {
        SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Employees", connection);
        adapter.Fill(dataSet, "Employees");
        
        DataTable employeesTable = dataSet.Tables["Employees"];
        foreach (DataRow row in employeesTable.Rows)
        {
            Console.WriteLine($"{row["FirstName"]} {row["LastName"]}");
        }
    }
} }

~~~

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

. What is connection pooling and how does it benefit ADO.NET performance?

A

Connection pooling is a technique used to minimize the cost of opening and closing database connections. Instead of opening a new connection for every request, ADO.NET reuses existing connections from a pool of connections. When a connection is closed, it is returned to the pool, not actually closed, for reuse by another request. This reduces the overhead of establishing new connections and improves performance.

Benefits:

Faster Connection Establishment: Reusing existing connections speeds up subsequent database access.

Reduced Resource Usage: Connection pooling minimizes the number of physical connections, leading to more efficient resource utilization.

Scalability: Increases the scalability of applications by handling high volumes of database access with a limited number of actual connections.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Describe the process of managing database connections in ADO.NET. Include an example using SqlConnection.

A

: Managing database connections in ADO.NET involves creating a SqlConnection object, opening the connection, and closing it when done. It is important to use the using statement or explicitly close the connection to ensure resources are released properly. Connection strings are used to specify connection parameters.

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";
        
        using (SqlConnection connection = new SqlConnection(connectionString))
        {
            connection.Open();
            SqlCommand command = new SqlCommand("SELECT * FROM Employees", connection);
            SqlDataReader reader = command.ExecuteReader();
            
            while (reader.Read())
            {
                Console.WriteLine(reader["FirstName"]);
            }
        }
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the advantages of using parameterized queries in ADO.NET?

A

Parameterized queries provide several advantages:

Prevention of SQL Injection: By separating SQL code from data, parameterized queries prevent attackers from injecting malicious SQL.

Improved Performance: Reusing the query execution plan for parameterized queries improves performance since the database can cache the execution plan.

Security: Ensures that the data passed in parameters is treated as data, not executable code.

string query = "SELECT * FROM Employees WHERE Department = @Department";
SqlCommand command = new SqlCommand(query, connection);
command.Parameters.AddWithValue("@Department", "Sales");
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Explain how transactions are managed in ADO.NET. Provide an example of a transaction.

A

Explanation: Transactions in ADO.NET are used to ensure that a series of database operations are executed as a single unit, meaning either all operations are successful, or none are. You can begin a transaction using the BeginTransaction() method and commit or roll back the transaction based on success or failure.

using System;
using System.Data.SqlClient;

class Program
{
    static void Main()
    {
        string connectionString = "YourConnectionStringHere";

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

            // Begin the transaction
            SqlTransaction transaction = connection.BeginTransaction();

            // Create a command and assign it to the transaction
            SqlCommand command = connection.CreateCommand();
            command.Transaction = transaction;

            try
            {
                // Execute some commands within the transaction
                command.CommandText = "UPDATE Employees SET FirstName = 'John' WHERE EmployeeID = 1";
                command.ExecuteNonQuery();

                command.CommandText = "UPDATE Employees SET FirstName = 'Jane' WHERE EmployeeID = 2";
                command.ExecuteNonQuery();

                // Commit the transaction if both updates succeed
                transaction.Commit();
                Console.WriteLine("Transaction committed successfully.");
            }
            catch (Exception ex)
            {
                // Rollback the transaction if an error occurs
                transaction.Rollback();
                Console.WriteLine("Transaction rolled back due to an error: " + ex.Message);
            }
        }
    }
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q
A
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Explain the difference between ExecuteScalar, ExecuteNonQuery, and ExecuteReader methods of the SqlCommand class.

A

ExecuteScalar(): Executes a query that returns a single value (e.g., aggregate functions like COUNT, SUM).

ExecuteNonQuery(): Executes a query that doesn’t return any result set, such as INSERT, UPDATE, DELETE, and DDL commands.

ExecuteReader(): Executes a query that returns a result set, typically used for SELECT queries. It returns a SqlDataReader to read the data.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

How can you handle exceptions in ADO.NET? Provide a code example.

A

Explanation: In ADO.NET, exceptions can be handled using try-catch blocks. You should catch exceptions like SqlException to handle database-related errors.

try
{
    using (SqlConnection connection = new SqlConnection("YourConnectionString"))
    {
        connection.Open();
        SqlCommand command = new SqlCommand("SELECT * FROM Employees", connection);
        SqlDataReader reader = command.ExecuteReader();
    }
}
catch (SqlException ex)
{
    Console.WriteLine("Database error: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("General error: " + ex.Message);
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly