10.2 Setting up database and writing points
- If needed, start from the project up to chapter 9. This contains the classes as you left them at the end of chapter 9.
- The SQL script
CreateInsertScriptShapes.sqlis available in theDatafolder. Run it in MySQL Workbench. You will have a databaseShapeswith tablesCircle,Shape,Point, andRectangle, plus a user and password. - Add the MySql.Data NuGet package to your project:
dotnet add package MySql.Data -
Add the following constant to your
Programclass (above the Main method):1 2
private const string ConnectionString = "Server=localhost;Database=Shapes;User=userShapes;Password=userShapesPW;";This connection string tells MySQL how to connect:
-Server=localhost: connect to a MySQL server running on your own machine.
-Database=Shapes: use theShapesdatabase that you created with the SQL script.
-User=userShapes: log in with the application useruserShapes.
-Password=userShapesPW: use the password that was created for this user.
Together these parts must match the server, database, user, and password you actually have in MySQL Workbench; if any part is different, the connection will fail. -
Add the following code to your
Mainmethod: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
using MySql.Data.MySqlClient; MySqlConnection? connection = null; try { connection = new MySqlConnection(ConnectionString); connection.Open(); } catch (MySqlException ex) { Console.WriteLine("SQL Exception: " + ex.Message); } if (connection != null) { Console.WriteLine("Connection established!"); string sql = "INSERT INTO Point VALUES (3, 5);"; try { MySqlCommand command = new MySqlCommand(sql, connection); command.ExecuteNonQuery(); connection.Close(); } catch (MySqlException ex) { Console.WriteLine(ex); } }- The query is in the string
sql. In this case, a point with coordinates (3, 5) is added to thePointtable. - The command is executed via the connection.
- After execution, the connection can be closed.
- The query is in the string
-
Run your program and verify in Workbench that the point was created.