Connecting to a database using a WPF application

2019-04-13 11:09发布

问题:

I've started getting into WPF not so long ago.
As I'm in the stage of learning MVVM, I'm using THIS tutorial.

Following that tutorial I now have a basic project that involves products.
The next thing I want to do, is learn how to connect to a database and store/retrieve information from it.

My question is, what are the available ways to connect to a database? what is the best, efficient way to do it?

Also, can WPF applications connect to an hosted mysql database (the ones used for websites)?

I'm using VS2012 if that makes any difference.

Excuse my newbie-ness! I'm still just a beginner! Thank you in advance!

回答1:

Check this: EF code first with oracle, mysql, etc.

At the end, there is download link for a sample.

As for WPF, i would recommend to read some tutorials if you´re not familiar with it. Searching for WPF and EF together will lead to a lot of more or less helpful tutorials and blogs, etc. But i would recommend playing around with the Entityframework and the code-first approach first.



回答2:

Setting up Entity Framework takes too long + Compatibility issues, thus not efficient. Use this:

 SqlConnection connection = new SqlConnection
 {
      ConnectionString = ConfigurationManager.ConnectionStrings["Connection_String_Name"].ConnectionString
 };

 connection.Open();

 SqlCommand cmd = new SqlCommand("Query_For_What_You_Wanna_Do");
 cmd.ExecuteNonQuery();

 connection.Close();