C#实现创建一个实体类-连接数据库-配置实体类-实现增删改查方法【同步异步+事务】 – 三郎君的日常

C# · 2023年5月23日 0

C#实现创建一个实体类-连接数据库-配置实体类-实现增删改查方法【同步异步+事务】

实现步骤如下:

1.  安装MySQL.Data包

在Visual  Studio的NuGet包管理器中搜索MySQL.Data,安装MySQL.Data包。

2.  创建学生实体类

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
    public string Gender { get; set; }
    public string Department { get; set; }
}

3.  配置连接MySQL数据库

在App.config文件中添加MySQL数据库连接字符串:

<connectionStrings>
  <add name="MySQLConnectionString" connectionString="server=localhost;port=3306;user id=root;password=123456;database=mydatabase" providerName="MySql.Data.MySqlClient" />
</connectionStrings>

4.  实现增删改查方法

using MySql.Data.MySqlClient;

public static class DataAccess
{
    private static MySqlConnection GetConnection()
    {
        string connectionString = ConfigurationManager.ConnectionStrings["MySQLConnectionString"].ConnectionString;
        MySqlConnection connection = new MySqlConnection(connectionString);
        return connection;
    }

    public static List<Student> GetAllStudents()
    {
        List<Student> students = new List<Student>();

        using (MySqlConnection connection = GetConnection())
        {
            connection.Open();
            string query = "SELECT * FROM students";
            using (MySqlCommand command = new MySqlCommand(query, connection))
            {
                using (MySqlDataReader reader = command.ExecuteReader())
                {
                    while (reader.Read())
                    {
                        Student student = new Student
                        {
                            Id = Convert.ToInt32(reader["id"]),
                            Name = reader["name"].ToString(),
                            Age = Convert.ToInt32(reader["age"]),
                            Gender = reader["gender"].ToString(),
                            Department = reader["department"].ToString()
                        };
                        students.Add(student);
                    }
                }
            }
        }

        return students;
    }

    public static void AddStudent(Student student)
    {
        using (MySqlConnection connection = GetConnection())
        {
            connection.Open();
            string query = "INSERT INTO students(name, age, gender, department) VALUES(@name, @age, @gender, @department)";
            using (MySqlCommand command = new MySqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@name", student.Name);
                command.Parameters.AddWithValue("@age", student.Age);
                command.Parameters.AddWithValue("@gender", student.Gender);
                command.Parameters.AddWithValue("@department", student.Department);
                command.ExecuteNonQuery();
            }
        }
    }

    public static void UpdateStudent(Student student)
    {
        using (MySqlConnection connection = GetConnection())
        {
            connection.Open();
            string query = "UPDATE students SET name = @name, age = @age, gender = @gender, department = @department WHERE id = @id";
            using (MySqlCommand command = new MySqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@id", student.Id);
                command.Parameters.AddWithValue("@name", student.Name);
                command.Parameters.AddWithValue("@age", student.Age);
                command.Parameters.AddWithValue("@gender", student.Gender);
                command.Parameters.AddWithValue("@department", student.Department);
                command.ExecuteNonQuery();
            }
        }
    }

    public static void DeleteStudent(int id)
    {
        using (MySqlConnection connection = GetConnection())
        {
            connection.Open();
            string query = "DELETE FROM students WHERE id = @id";
            using (MySqlCommand command = new MySqlCommand(query, connection))
            {
                command.Parameters.AddWithValue("@id", id);
                command.ExecuteNonQuery();
            }
        }
    }
}

5.  测试

添加一个学生:

Student student = new Student
{
    Name = "张三",
    Age = 20,
    Gender = "男",
    Department = "信息工程学院"
};
DataAccess.AddStudent(student);

查询所有学生:

List<Student> students = DataAccess.GetAllStudents();
foreach (var student in students)
{
    Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}", student.Id, student.Name, student.Age, student.Gender, student.Department);
}

更新一个学生:

int idToUpdate = 1;
Student student = DataAccess.GetAllStudents().FirstOrDefault(s => s.Id == idToUpdate);
if (student != null)
{
    student.Name = "李四";
    student.Age = 22;
    student.Gender = "女";
    student.Department = "软件工程学院";
    DataAccess.UpdateStudent(student);
}

删除一个学生:

int idToDelete = 2;
DataAccess.DeleteStudent(idToDelete);

注意:以上代码仅仅是一个简短的示例,实际应用中可能需要更加健壮和严谨的判断等。

Java异步增删改查实现:

import java.util.List;
import java.util.concurrent.CompletableFuture;

public interface UserServiceAsync {

    CompletableFuture<Void> add(User user);

    CompletableFuture<Void> deleteById(String id);

    CompletableFuture<Void> update(User user);

    CompletableFuture<User> findById(String id);

    CompletableFuture<List<User>> findAll();
}

public class UserServiceAsyncImpl implements UserServiceAsync {

    private UserDao userDao;

    public UserServiceAsyncImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public CompletableFuture<Void> add(User user) {
        return CompletableFuture.runAsync(() -> userDao.add(user));
    }

    @Override
    public CompletableFuture<Void> deleteById(String id) {
        return CompletableFuture.runAsync(() -> userDao.deleteById(id));
    }

    @Override
    public CompletableFuture<Void> update(User user) {
        return CompletableFuture.runAsync(() -> userDao.update(user));
    }

    @Override
    public CompletableFuture<User> findById(String id) {
        return CompletableFuture.supplyAsync(() -> userDao.findById(id));
    }

    @Override
    public CompletableFuture<List<User>> findAll() {
        return CompletableFuture.supplyAsync(() -> userDao.findAll());
    }
}

Java同步增删改查实现

import java.util.List;

public interface UserServiceSync {

    void add(User user);

    void deleteById(String id);

    void update(User user);

    User findById(String id);

    List<User> findAll();
}

public class UserServiceSyncImpl implements UserServiceSync {

    private UserDao userDao;

    public UserServiceSyncImpl(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public void add(User user) {
        userDao.add(user);
    }

    @Override
    public void deleteById(String id) {
        userDao.deleteById(id);
    }

    @Override
    public void update(User user) {
        userDao.update(user);
    }

    @Override
    public User findById(String id) {
        return userDao.findById(id);
    }

    @Override
    public List<User> findAll() {
        return userDao.findAll();
    }
}

C#实现同步增删改查

using System.Collections.Generic;

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class StudentRepository
{
    private List<Student> students;

    public StudentRepository()
    {
        students = new List<Student>();
    }

    public void Add(Student student)
    {
        students.Add(student);
    }

    public void Update(int id, Student student)
    {
        Student oldStudent = students.Find(s => s.Id == id);
        if (oldStudent != null)
        {
            oldStudent.Name = student.Name;
            oldStudent.Age = student.Age;
        }
    }

    public void Delete(int id)
    {
        Student student = students.Find(s => s.Id == id);
        if (student != null)
        {
            students.Remove(student);
        }
    }

    public Student GetById(int id)
    {
        return students.Find(s => s.Id == id);
    }

    public List<Student> GetAll()
    {
        return students;
    }
}

C#实现异步增删改查

using System.Collections.Generic;
using System.Threading.Tasks;

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

public class StudentRepository
{
    private List<Student> students;

    public StudentRepository()
    {
        students = new List<Student>();
    }

    public async Task AddAsync(Student student)
    {
        await Task.Run(() => students.Add(student));
    }

    public async Task UpdateAsync(int id, Student student)
    {
        await Task.Run(() =>
        {
            Student oldStudent = students.Find(s => s.Id == id);
            if (oldStudent != null)
            {
                oldStudent.Name = student.Name;
                oldStudent.Age = student.Age;
            }
        });
    }

    public async Task DeleteAsync(int id)
    {
        await Task.Run(() =>
        {
            Student student = students.Find(s => s.Id == id);
            if (student != null)
            {
                students.Remove(student);
            }
        });
    }

    public async Task<Student> GetByIdAsync(int id)
    {
        return await Task.Run(() => students.Find(s => s.Id == id));
    }

    public async Task<List<Student>> GetAllAsync()
    {
        return await Task.Run(() => students);
    }
}

C#加上事务实现对一个学生类增删改查异步和同步

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; }
    public int Age { get; set; }
}

接下来分别示例实现事务的同步和异步增删改查。我们可以利用ADO.NET或Entity  Framework等框架来操作数据库进行事务处理。

##  同步实现

###  增加一个学生

//增加
public void AddStudentSync(Student student)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        var transaction = connection.BeginTransaction();
        try
        {
            var command = new SqlCommand("INSERT INTO Students (Name, Age) VALUES (@Name, @Age)", connection, transaction);
            command.Parameters.AddWithValue("@Name", student.Name);
            command.Parameters.AddWithValue("@Age", student.Age);
            command.ExecuteNonQuery();

            transaction.Commit();
        }
        catch(Exception)
        {
            transaction.Rollback();
            throw;
        }
    }
}
//删除
public void DeleteStudentSync(int studentId)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        var transaction = connection.BeginTransaction();
        try
        {
            var command = new SqlCommand("DELETE FROM Students WHERE Id = @Id", connection, transaction);
            command.Parameters.AddWithValue("@Id", studentId);
            command.ExecuteNonQuery();

            transaction.Commit();
        }
        catch(Exception)
        {
            transaction.Rollback();
            throw;
        }
    }
}
//修改
public void UpdateStudentSync(Student student)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        var transaction = connection.BeginTransaction();
        try
        {
            var command = new SqlCommand("UPDATE Students SET Name = @Name, Age = @Age WHERE Id = @Id", connection, transaction);
            command.Parameters.AddWithValue("@Id", student.Id);
            command.Parameters.AddWithValue("@Name", student.Name);
            command.Parameters.AddWithValue("@Age", student.Age);
            command.ExecuteNonQuery();

            transaction.Commit();
        }
        catch(Exception)
        {
            transaction.Rollback();
            throw;
        }
    }
}
//查询
public Student GetStudentSync(int studentId)
{
    using (var connection = new SqlConnection(connectionString))
    {
        connection.Open();
        var command = new SqlCommand("SELECT Id, Name, Age FROM Students WHERE Id = @Id", connection);
        command.Parameters.AddWithValue("@Id", studentId);
        var reader = command.ExecuteReader();
        if(reader.Read())
        {
            return new Student
            {
                Id = reader.GetInt32(reader.GetOrdinal("Id")),
                Name = reader.GetString(reader.GetOrdinal("Name")),
                Age = reader.GetInt32(reader.GetOrdinal("Age"))
            };
        }
        return null;
    }
}
##  异步实现

//增加
public async Task AddStudentAsync(Student student)
{
    using (var connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
        var transaction = connection.BeginTransaction();
        try
        {
            var command = new SqlCommand("INSERT INTO Students (Name, Age) VALUES (@Name, @Age)", connection, transaction);
            command.Parameters.AddWithValue("@Name", student.Name);
            command.Parameters.AddWithValue("@Age", student.Age);
            await command.ExecuteNonQueryAsync();

            transaction.Commit();
        }
        catch(Exception)
        {
            transaction.Rollback();
            throw;
        }
    }
}
//删除
public async Task DeleteStudentAsync(int studentId)
{
    using (var connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
        var transaction = connection.BeginTransaction();
        try
        {
            var command = new SqlCommand("DELETE FROM Students WHERE Id = @Id", connection, transaction);
            command.Parameters.AddWithValue("@Id", studentId);
            await command.ExecuteNonQueryAsync();

            transaction.Commit();
        }
        catch(Exception)
        {
            transaction.Rollback();
            throw;
        }
    }
}
//修改
public async Task UpdateStudentAsync(Student student)
{
    using (var connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
        var transaction = connection.BeginTransaction();
        try
        {
            var command = new SqlCommand("UPDATE Students SET Name = @Name, Age = @Age WHERE Id = @Id", connection, transaction);
            command.Parameters.AddWithValue("@Id", student.Id);
            command.Parameters.AddWithValue("@Name", student.Name);
            command.Parameters.AddWithValue("@Age", student.Age);
            await command.ExecuteNonQueryAsync();

            transaction.Commit();
        }
        catch(Exception)
        {
            transaction.Rollback();
            throw;
        }
    }
}
//查询
public async Task<Student> GetStudentAsync(int studentId)
{
    using (var connection = new SqlConnection(connectionString))
    {
        await connection.OpenAsync();
        var command = new SqlCommand("SELECT Id, Name, Age FROM Students WHERE Id = @Id", connection);
        command.Parameters.AddWithValue("@Id", studentId);
        var reader = await command.ExecuteReaderAsync();
        if(await reader.ReadAsync())
        {
            return new Student
            {
                Id = reader.GetInt32(reader.GetOrdinal("Id")),
                Name = reader.GetString(reader.GetOrdinal("Name")),
                Age = reader.GetInt32(reader.GetOrdinal("Age"))
            };
        }
        return null;
    }
}