当前位置:首页 > 行业动态 > 正文

c#对数据库进行增删改查

C#对数据库进行增删改查:该语言通过相关类库和对象操作数据库,实现数据的增加、删除、修改与查询功能。

在C#中对数据库进行增删改查操作是常见的需求,以下是详细的介绍:

一、连接数据库

在进行增删改查操作之前,需要先连接到数据库,通常使用System.Data.SqlClient命名空间中的SqlConnection类来建立连接。

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

二、增加数据(Insert)

使用SqlCommand类和ExecuteNonQuery方法来执行插入操作,以下是一个将新的学生信息添加到学生表中的示例:

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

三、删除数据(Delete)

同样使用SqlCommand类和ExecuteNonQuery方法,指定要删除的数据行并执行删除操作,例如从学生表中删除指定姓名的学生信息:

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

四、更新数据(Update)

使用UPDATE命令和ExecuteNonQuery方法来更新数据库中的数据,例如在学生表中将指定学生的年龄更新为新的值:

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

五、查询数据(Select)

查询数据可以使用SqlCommand类和ExecuteReader方法,将查询结果存储到SqlDataReader对象中,然后进行处理,例如查询学生表中的所有学生信息:

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 reader = command.ExecuteReader();
    // 遍历查询结果
    while (reader.Read())
    {
        Console.WriteLine("Name: " + reader["Name"].ToString());
        Console.WriteLine("Age: " + reader["Age"].ToString());
        Console.WriteLine("Gender: " + reader["Gender"].ToString());
    }
}
catch (Exception ex)
{
    // 处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    // 关闭数据库连接
    connection.Close();
}

六、FAQs

**问题1:如何在C#中使用参数化查询来防止SQL注入攻击?

答:在C#中,可以使用参数化查询来防止SQL注入攻击,通过将参数传递给SqlCommand对象的Parameters集合,而不是直接拼接SQL字符串,可以有效地避免SQL注入风险。

string connectionString = "Data Source=myServerAddress;Initial Catalog=myDataBase; User ID=myUsername;Password=myPassword;";
SqlConnection connection = new SqlConnection(connectionString);
try
{
    // 打开数据库连接
    connection.Open();
    // 定义SQL语句,使用参数占位符@paramName
    string sql = "INSERT INTO Students (Name, Age, Gender) VALUES (@Name, @Age, @Gender);";
    // 创建SqlCommand对象,并添加参数
    SqlCommand command = new SqlCommand(sql, connection);
    command.Parameters.AddWithValue("@Name", "John");
    command.Parameters.AddWithValue("@Age", 20);
    command.Parameters.AddWithValue("@Gender", "Male");
    // 执行SQL语句并返回受影响的行数
    int rowsAffected = command.ExecuteNonQuery();
    Console.WriteLine("Rows Affected: " + rowsAffected);
}
catch (Exception ex)
{
    // 处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    // 关闭数据库连接
    connection.Close();
}

**问题2:如何在C#中使用事务来确保多个数据库操作的原子性?

答:在C#中,可以使用Transaction类来管理事务,通过创建一个Transaction对象,并将其与SqlConnection对象关联,可以确保多个数据库操作要么全部成功,要么全部回滚。

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();
    // 开始事务
    SqlTransaction transaction = connection.BeginTransaction();
    try
    {
        // 定义第一个SQL语句并创建SqlCommand对象
        string sql1 = "INSERT INTO Students (Name, Age, Gender) VALUES (@Name, @Age, @Gender);";
        SqlCommand command1 = new SqlCommand(sql1, connection, transaction);
        command1.Parameters.AddWithValue("@Name", "John");
        command1.Parameters.AddWithValue("@Age", 20);
        command1.Parameters.AddWithValue("@Gender", "Male");
        command1.ExecuteNonQuery();
        // 定义第二个SQL语句并创建SqlCommand对象
        string sql2 = "UPDATE Students SET Age = 21 WHERE Name = 'John';";
        SqlCommand command2 = new SqlCommand(sql2, connection, transaction);
        command2.ExecuteNonQuery();
        // 提交事务
        transaction.Commit();
    }
    catch (Exception ex)
    {
        // 如果发生异常,则回滚事务
        transaction.Rollback();
        throw ex; // 重新抛出异常以便调用者知道发生了错误
    }
}
catch (Exception ex)
{
    // 处理异常
    Console.WriteLine(ex.Message);
}
finally
{
    // 关闭数据库连接
    connection.Close();
}
0