1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97
| using System; using System.Collections.Generic; using System.Threading.Tasks; using Final.DataBase;
class Program { static async Task Main(string[] args) { string connectionString = "Your_Connection_String_Here"; MDataBase db = MDataBase.GetInstance(connectionString);
try { var newPerson = new Person { Name = "Alice", Age = 30, BirthDate = new DateTime(1993, 5, 1) }; string insertQuery = "INSERT INTO Person (Name, Age, BirthDate) VALUES (@Name, @Age, @BirthDate)"; bool insertResult = await db.Insert(newPerson, insertQuery); Console.WriteLine($"Insert successful: {insertResult}");
string selectQuery = "SELECT Id, Name, Age, BirthDate FROM Person"; List<Person> persons = await db.Select<Person>(selectQuery, null); foreach (var person in persons) { Console.WriteLine($"Id: {person.Id}, Name: {person.Name}, Age: {person.Age}, BirthDate: {person.BirthDate}"); }
var updatePerson = persons[0]; updatePerson.Age = 31; string updateQuery = "UPDATE Person SET Name = @Name, Age = @Age, BirthDate = @BirthDate WHERE Id = @Id"; bool updateResult = await db.Update(updatePerson, updateQuery); Console.WriteLine($"Update successful: {updateResult}");
var deletePerson = persons[0]; string deleteQuery = "DELETE FROM Person WHERE Id = @Id"; bool deleteResult = await db.Delete(deletePerson, deleteQuery); Console.WriteLine($"Delete successful: {deleteResult}");
bool transactionResult = await db.ExecuteTransactionAsync( async (transaction) => { string personInsertQuery = "INSERT INTO Person (Name, Age) VALUES (@Name, @Age)"; var personParams = new[] { new SqlParameter("@Name", "John Doe"), new SqlParameter("@Age", 35) }; int personInsertResult = await db.ExecuteNonQueryAsync(personInsertQuery, personParams, transaction);
return personInsertResult; }, async (transaction) => { string personIdQuery = "SELECT SCOPE_IDENTITY()"; object personIdResult = await db.ExecuteScalar("SELECT SCOPE_IDENTITY()", null); int personId = Convert.ToInt32(personIdResult);
string addressInsertQuery = "INSERT INTO Address (PersonId, AddressLine) VALUES (@PersonId, @AddressLine)"; var addressParams = new[] { new SqlParameter("@PersonId", personId), new SqlParameter("@AddressLine", "123 Main Street") }; return await db.ExecuteNonQueryAsync(addressInsertQuery, addressParams, transaction); } );
Console.WriteLine($"Transaction completed successfully: {transactionResult}"); } catch (Exception ex) { Console.WriteLine($"An error occurred: {ex.Message}"); } finally { db.Close(); } } }
|