C# SQL Server database basic operations (add, delete, modify, check)

C# connecting to the database is a very important task. In software development, we usually need to store data in the database, and need to use C# code to interact with the database in the application. In this article, we will learn how to use C# to connect to the database, and how to complete common CRUD operations.

1. Connect to the database

To connect to the database first, you need to use the SqlConnection class in the System.Data.SqlClient namespace. Here is a basic example of connecting to a Microsoft SQL Server database:

using System.Data.SqlClient;

string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

try
{
    //打开数据库连接
    connection.Open();

    //执行数据库操作
    //...

}
catch (Exception ex)
{
    //处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    //关闭数据库连接
    connection.Close();
}

In the above code, we defined a connection string, which contains information such as the server name of the database, database name, user name and password. Then, we use the SqlConnection class to create a connection object, and use the Open method to open the database connection. After the connection is successful, we can perform related operations.

2. Increase data

To add data to the database, you need to use the SqlCommand class and the ExecuteNonQuery method. Here is an example of adding a new student information to the student table:

using System.Data.SqlClient;

string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

try
{
    //打开数据库连接
    connection.Open();

    //定义SQL语句
    string sql = "INSERT INTO Students (Name, Age, Gender) VALUES ('John', 20, 'Male');";

    //创建SqlCommand对象
    SqlCommand command = new SqlCommand(sql, connection);

    //执行SQL语句
    int rowsAffected = command.ExecuteNonQuery();
    Console.WriteLine("Rows Affected: " + rowsAffected);
}
catch (Exception ex)
{
    //处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    //关闭数据库连接
    connection.Close();
}

In the above code, we have successfully connected to the database and defined a SQL statement using the SqlCommand class. Then, we created a SqlCommand object and passed the SQL statement and database connection as parameters to it. Next, we call the ExecuteNonQuery method to execute the SQL statement and return the number of affected rows.

3. Delete data

To delete data from the database, you can use the same method, specify the data row to be deleted, and use the DELETE command. Here is an example to delete the student information of the specified name from the student table:

using System.Data.SqlClient;

string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

try
{
    //打开数据库连接
    connection.Open();

    //定义SQL语句
    string sql = "DELETE FROM Students WHERE Name = 'John';";

    //创建SqlCommand对象
    SqlCommand command = new SqlCommand(sql, connection);

    //执行SQL语句
    int rowsAffected = command.ExecuteNonQuery();
    Console.WriteLine("Rows Affected: " + rowsAffected);
}
catch (Exception ex)
{
    //处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    //关闭数据库连接
    connection.Close();
}

In the above code, we use the same method to connect to the database and use the DELETE command to delete the student named "John" from the students table.

4. Update data

To update data in the database, you can use the UPDATE command. Here's an example that updates the specified student's age with the new value in the students table:

using System.Data.SqlClient;

string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

try
{
    //打开数据库连接
    connection.Open();

    //定义SQL语句
    string sql = "UPDATE Students SET Age = 21 WHERE Name = 'John';";

    //创建SqlCommand对象
    SqlCommand command = new SqlCommand(sql, connection);

    //执行SQL语句
    int rowsAffected = command.ExecuteNonQuery();
    Console.WriteLine("Rows Affected: " + rowsAffected);
}
catch (Exception ex)
{
    //处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    //关闭数据库连接
    connection.Close();
}

In the above code, we use the UPDATE command to update the age of the student named "John" to 21.

5. Query data

To query data from the database, you can use the SELECT command, among other commands. The following is an example of querying all student information in the student table:

using System.Data.SqlClient;

string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);

try
{
    //打开数据库连接
    connection.Open();

    //定义SQL语句
    string sql = "SELECT * FROM Students;";

    //创建SqlCommand对象
    SqlCommand command = new SqlCommand(sql, connection);

    //执行SQL语句
    SqlDataReader dataReader = command.ExecuteReader();

    //遍历查询结果
    while (dataReader.Read())
    {
        Console.WriteLine("{0}\t{1}\t{2}", dataReader["Name"], dataReader["Age"], dataReader["Gender"]);
    }

    //关闭DataReader
    dataReader.Close();
}
catch (Exception ex)
{
    //处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    //关闭数据库连接
    connection.Close();
}

In the above code, we use the SELECT command to query all student information in the student table. We create a SqlDataReader instance, and use its Read method to traverse the query results, and finally call the Close method to close it.

Summarize

To connect to the database in C#, we need to use classes such as SqlConnection, SqlCommand and SqlDataReader in the System.Data.SqlClient namespace. When connecting to the database, you need to specify the database connection string, and make sure to provide the correct SQL statement and connection object when using SqlCommand. Using these classes, we can easily perform common CRUD operations, as well as many other operations. Mastering the method of database connection can make it easier for us to develop excellent C# applications.

Guess you like

Origin blog.csdn.net/naer_chongya/article/details/130411520