10.4 DbAccess class
- Create a new folder
Data(orDatabase) in your project. -
Create a class
DbAccess: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
namespace Geometry.Data { public class DbAccess { private readonly string _connectionString; private MySqlConnection? _connection; public DbAccess(string connectionString) { _connectionString = connectionString; } public void OpenConnection() { _connection = new MySqlConnection(_connectionString); _connection.Open(); } public MySqlConnection GetConnection() { if (_connection == null) throw new InvalidOperationException("Connection not opened."); return _connection; } public void CloseConnection() { _connection?.Close(); } } }All code related to creating a connection to a database is placed in a separate class. We can then create objects that handle the connection. The code in
Mainis greatly simplified. The code in theDbAccessclass becomes reusable. The class diagram of theDbAccessclass is as follows:- The attribute
_connectionholds the active connection to the DBMS. - The constructor needs the connection string, for example:
Server=localhost;Database=Shapes;User=userShapes;Password=userShapesPW; - In that connection string:
Serveris the MySQL host,Databaseis the schema to use,
Useris the login name, andPasswordis the login password. - The three methods
OpenConnection(),GetConnection(), andCloseConnection()are now placed in theDbAccessclass.
- The attribute
-
Remove the constant you added above the
Mainmethod. -
Change the code in your
Mainmethod to useDbAccess:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
DbAccess dbAccess = new DbAccess("Server=localhost;Database=Shapes;User=userShapes;Password=userShapesPW;"); dbAccess.OpenConnection(); var connection = dbAccess.GetConnection(); string sql = "SELECT * FROM Point;"; try { MySqlCommand command = new MySqlCommand(sql, connection); using MySqlDataReader reader = command.ExecuteReader(); while (reader.Read()) { double x = reader.GetDouble("xcoordinate"); double y = reader.GetDouble("ycoordinate"); Console.WriteLine($"({x:F2}, {y:F2})"); } } catch (MySqlException ex) { Console.WriteLine(ex); } dbAccess.CloseConnection();- You create a new instance of the
DbAccessclass with the correct parameters to access the database. - The
dbAccessobject is then used to open, provide, and close the connection.
- You create a new instance of the
-
Run your program. The output is the same as in 10.3. step 1.