11.4 Refactor CircleDao
-
Change the first lines of the
CircleDaoclass definition:1 2 3 4 5
public class CircleDao : AbstractDao { public CircleDao(DbAccess dbAccess) : base(dbAccess) { } -
Add a helper method below
SaveCircle:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
private int SaveShape(string color) { string sql = "INSERT INTO Shape(color) VALUES (@color);"; int primaryKey = 0; try { var cmd = new MySqlCommand(sql, _dbAccess.GetConnection()); cmd.Parameters.AddWithValue("@color", color); cmd.ExecuteNonQuery(); cmd.CommandText = "SELECT LAST_INSERT_ID();"; primaryKey = Convert.ToInt32(cmd.ExecuteScalar()); } catch (MySqlException ex) { Console.WriteLine(ex); } return primaryKey; } -
Simplify the
SaveCirclemethod:1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
public void SaveCircle(Circle circle) { int primaryKey = SaveShape(circle.Color); string sql = "INSERT INTO Circle VALUES (@id, @radius, @x, @y);"; try { var cmd = new MySqlCommand(sql, _dbAccess.GetConnection()); cmd.Parameters.AddWithValue("@id", primaryKey); cmd.Parameters.AddWithValue("@radius", circle.Radius); cmd.Parameters.AddWithValue("@x", circle.Center.X); cmd.Parameters.AddWithValue("@y", circle.Center.Y); cmd.ExecuteNonQuery(); } catch (MySqlException ex) { Console.WriteLine(ex); } } -
Add the following UML class diagram:
The
PointDaoandCircleDaoclasses are subclasses ofAbstractDao. Therefore, these classes have access to the attributes ofAbstractDao.- They also have access to the shared methods used to handle SQL statements.
- The
PointDaoclass only contains methods that are specific to objects of thePointclass. - The
CircleDaoclass only contains methods that are specific to objects of theCircleclass.
-
Change the code in your
Mainmethod:1 2 3 4 5 6 7 8 9 10 11 12
DbAccess dbAccess = new DbAccess("Server=localhost;Database=Shapes;User=userShapes;Password=userShapesPW;"); dbAccess.OpenConnection(); PointDao pointDao = new PointDao(dbAccess); pointDao.SavePoint(new Point(8, -12)); foreach (Point point in pointDao.GetPoints()) Console.WriteLine(point); CircleDao circleDao = new CircleDao(dbAccess); circleDao.SaveCircle(new Circle(6.5, new Point(-2.3, -1.3), "purple")); dbAccess.CloseConnection(); -
Run your program and verify in Workbench that the point and circle were added.