Using MySQL Database With UWP

Design MySQL DB

We can use many tools to connect to the DB, but here we'll use the official MySQL Workbench.

MySQL Workbench can be downloaded from here along with the Connectors.

What's a Connector?

A Connector is the DB driver that you include in your project to be able to interact and connect to your DB through your application.

After installing the Workbench with the default settings open it:

workbenchMain

Then we click the Add button to add a new DB:

AddButton

We insert the DB info then click Ok.

Now we click the New DB to establish a connection.

ClickDB

Here you can do whatever you want to your DB. let's go and add a Table (That's what you will usually do).

createTable1

Now we start adding the columns we need at our DB, in this case we'll need only two columns:

  • idtodo: INT, Primary Key, Not Null, Unique, Auto Incremental
  • whatToDO: varchar(200)

createTable2

And

createTable3

Then we click apply, wait for a little bit, then we review or add any SQL Script we need, then click Apply in the wizard.

Note:

You can see the script for creating the table, you can absolutely go and execute your script directly without having to walkthrough what I did here.

createTable4

The table is created successfully and ready to use!

createTable5

UWP Demo (Basic Todo app)

Before we begin please note that the Dreamspark free MySQL is limited to four concurrent connections. So, it will be optimal for your private use or for testing purposes.

What we'll do?

  • Create the UWP Project
  • Reference the connector
  • Implementing our MVVM (Model-View-ViewModel)

Creating the project

We click File, New Project, then from the Installed List we click -> Visual C#, Windows, Universal, then pick the UWP Project: Blank App (Universal Windows).

Reference the connector

addref

Then we click browse and go to the following path, please note that the "Connector.NET 6.9" version might differ by the time you're reading this so you should go and look it up yourself.

C:\Program Files (x86)\MySQL\Connector.NET 6.9\Assemblies\RT

We select the connector then we're ready to go.

Implementing the MVVM

We'll only create one page that contains a list of our Todo items, and a TextBox with a button to add the Text Box content as a new Todo.

Todo Model:

  1. public class Todo    
  2. {    
  3.     public string whatToDO { getset; }    
  4.     public Todo(string what)    
  5.     {    
  6.         whatToDO = what;    
  7.     }    
  8. }    
ViewModel (TodoViewModel.cs):
  1. public class TodoViewModel    
  2. {    
  3.     private static TodoViewModel _todoViewModel = new TodoViewModel();    
  4.     private ObservableCollection<Todo> _allToDos = new ObservableCollection<Todo>();    
  5.   
  6.     public ObservableCollection<Todo> AllTodos    
  7.     {    
  8.         get    
  9.         {    
  10.             return _todoViewModel._allToDos;    
  11.         }    
  12.     }    
  13.   
  14.     public IEnumerable<Todo> GetTodos()    
  15.     {    
  16.         try    
  17.         {    
  18.   
  19.             using (MySqlConnection connection = new MySqlConnection("Your connectionString + SslMode=None"))    
  20.             {    
  21.                 connection.Open();    
  22.                 MySqlCommand getCommand = connection.CreateCommand();    
  23.                 getCommand.CommandText = "SELECT whatToDO FROM todo";    
  24.                 using (MySqlDataReader reader = getCommand.ExecuteReader())    
  25.                 {    
  26.                     while (reader.Read())    
  27.                     {    
  28.                         _todoViewModel._allToDos.Add(new Todo(reader.GetString("whatToDO")));    
  29.                     }    
  30.                 }    
  31.             }    
  32.         }    
  33.         catch(MySqlException)    
  34.         {    
  35.             // Handle it :)    
  36.         }    
  37.             return _todoViewModel.AllTodos;    
  38.     }    
  39.   
  40.     public bool InsertNewTodo(string what)    
  41.     {    
  42.         Todo newTodo = new Todo(what);    
  43.         // Insert to the collection and update DB    
  44.         try    
  45.         {    
  46.             using (MySqlConnection connection = new MySqlConnection("Your connectionString + SslMode=None"))    
  47.             {    
  48.                 connection.Open();    
  49.                 MySqlCommand insertCommand = connection.CreateCommand();    
  50.                 insertCommand.CommandText = "INSERT INTO todo(whatToDO)VALUES(@whatToDO)";    
  51.                 insertCommand.Parameters.AddWithValue("@whatToDO", newTodo.whatToDO);    
  52.                 insertCommand.ExecuteNonQuery();    
  53.                 _todoViewModel._allToDos.Add(newTodo);    
  54.                 return true;    
  55.   
  56.             }    
  57.         }    
  58.         catch(MySqlException)    
  59.         {    
  60.             // Don't forget to handle it    
  61.             return false;    
  62.         }    
  63.   
  64.     }    
  65.   
  66.   
  67.     public TodoViewModel()    
  68.     { }    
  69. }   

What we did at GetTodos()

  • Established the connection
  • We opened it
  • Initializing the command ( Query )
  • Execute the command
  • Read incoming values and initializing new Todo objects then adding it to our ObservableCollection for data binding later.

What we did at InsertNewTodo (string what)

  • Started by creating new object of the Todo class & initialize it.
  • Established the connection
  • We opened the connection
  • Initializing the command ( Query )
  • Add the Query string
  • Add any parameters to the Query
  • Execute the command(Query)
  • Add the new Todo to the ObservableCollection
Note:

MySQL API for WinRT is not supporting SSL connection, So you'll have to turn it off by adding SslMode=None to your connection string.

App.xaml.cs code:

We just create a public static instance from our ViewModel to be consumed from all over the app.
  1. public static TodoViewModel TODO_VIEW_MODEL = new TodoViewModel();   

MainPage.xaml Code:

Within the Main Grid:

  1. <StackPanel Orientation="Vertical">    
  2.     <ListView x:Name="Todos">    
  3.         <ListView.ItemTemplate>    
  4.             <DataTemplate>    
  5.                 <StackPanel>    
  6.                     <TextBlock FontSize="25" Text="{Binding whatToDO}"/>    
  7.                 </StackPanel>    
  8.             </DataTemplate>    
  9.         </ListView.ItemTemplate>    
  10.     </ListView>    
  11.     <TextBox x:Name="NewTodoTxtBox" FontSize="25" Header="New Todo:"/>    
  12.     <Button x:Name="InsertTodoBtn" Click="InsertTodoBtn_Click" Content="Insert New Todo" Margin="0,20,0,0"/>    
  13. </StackPanel>   

MainPage Code-Behind(within MainPage Class):

  1. public sealed partial class MainPage : Page    
  2. {    
  3.         
  4.     public MainPage()    
  5.     {    
  6.         this.InitializeComponent();    
  7.     }    
  8.   
  9.     private void InsertTodoBtn_Click(object sender, RoutedEventArgs e)    
  10.     {    
  11.             
  12.         App.TODO_VIEW_MODEL.InsertNewTodo(NewTodoTxtBox.Text);    
  13.     }    
  14.   
  15.     protected override void OnNavigatedTo(NavigationEventArgs e)    
  16.     {    
  17.         Todos.ItemsSource = App.TODO_VIEW_MODEL.GetTodos();    
  18.     }    
  19. }  

We're done!

finalMySQL

Download the full sample from here.


Similar Articles