UWP链接数据库

从msdn文档https://docs.microsoft.com/en-us/windows/uwp/data-access/sql-server-databases 转载


首先nuget安装System.Data.SqlClient

使用的主要函数有

connectionstring是链接数据库请求字段

SqlConnection con = new SqlConnection(ConnectionString)
await con.OpenAsync();  //等待链接

然后我直接上代码好了

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.CompilerServices;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml.Controls;

namespace DataBaseHomeWork.Data
{
    //用来保存从数据库获得的数据
    public class DataBaseProduct : INotifyPropertyChanged
    {
        public int FID { get; set; }
        public string FName { get; set; }

        public event PropertyChangedEventHandler PropertyChanged;
        private void NotifyPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

    }
    public class DataBaseProductManager:INotifyPropertyChanged
    {
        private bool isBusy;
        private List mostRecentConnections;
        private string server;
        private bool? integratedSecurity;
        private string userId;
        private string password;
        private string connectionString;

        private List databases = new List();
        private string database;

        private SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder();

        public event PropertyChangedEventHandler PropertyChanged;

        /// 
        /// Gets or sets a value indicating whether this instance is busy.
        /// 
        public bool IsBusy
        {
            get { return isBusy; }
            set
            {
                isBusy = value;
                OnPropertyChanged();
            }
        }

        /// 
        /// Gets the most recently succesfully used server names.
        /// 
        public List MostRecentConnections
        {
            get { return mostRecentConnections; }
        }

        /// 
        /// Gets or sets the most recently succesfully used server name.
        /// 
        public string MostRecentConnection
        {
            get { return MostRecentConnections.FirstOrDefault(); }
            set
            {
                if (mostRecentConnections.Contains(value))
                {
                    if (mostRecentConnections.FirstOrDefault() == value)
                    {
                        return; // Already on top
                    }

                    mostRecentConnections.Remove(value);
                }

                mostRecentConnections.Insert(0, value);
                SaveMostRecentConnections();
            }
        }

        /// 
        /// Gets or sets the current server name.
        /// 
        public string Server
        {
            get { return server; }
            set
            {
                server = value;
                builder.DataSource = server;
                OnPropertyChanged();
            }
        }

        /// 
        /// Gets or sets whether integrated security is used for authentication.
        /// 
        public bool? IntegratedSecurity
        {
            get { return integratedSecurity; }
            set
            {
                integratedSecurity = value;
                if (integratedSecurity.HasValue)
                {
                    builder.IntegratedSecurity = integratedSecurity.Value;
                    OnPropertyChanged(nameof(SqlSecurity));
                }

                OnPropertyChanged();
            }
        }

        /// 
        /// Gets or sets the SQL user identifier.
        /// 
        public string UserId
        {
            get { return userId; }
            set
            {
                userId = value;
                builder.UserID = userId;
                OnPropertyChanged();
            }
        }

        /// 
        /// Gets or sets the SQL password.
        /// 
        public string Password
        {
            get { return password; }
            set
            {
                password = value;
                builder.Password = password;
                OnPropertyChanged();
            }
        }

        /// 
        /// Gets or sets the list of databases.
        /// 
        public List Databases
        {
            get { return databases; }
            set
            {
                databases = value;
                OnPropertyChanged();
            }
        }

        /// 
        /// Gets or sets the current database.
        /// 
        public string Database
        {
            get { return database; }
            set
            {
                database = value;
                builder.InitialCatalog = database;
                OnPropertyChanged();
            }
        }

        /// 
        /// Gets or sets the current connection string.
        /// 
        public string ConnectionString
        {
            get { return connectionString; }
            set
            {
                connectionString = value;
                builder.ConnectionString = connectionString;
                OnPropertyChanged();
            }
        }

        /// 
        /// Gets a value indicating whether SQL security is used for authentication.
        /// 
        public bool SqlSecurity
        {
            get { return IntegratedSecurity.HasValue && !IntegratedSecurity.Value; }
        }

        private void OnPropertyChanged([CallerMemberName] string propertyName = null)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

        /// 
        /// Tests the current connection and shows the result in a message dialog.
        /// 
        public async void GetValue()
        {

            IsBusy = true;


            try
            {
                using (SqlConnection con = new SqlConnection(builder.ConnectionString))
                {
                    string str = builder.ConnectionString;
                    await con.OpenAsync();
                }

                var msg = new MessageDialog("Connection Successful")
                {
                    Title = "OK"
                };

                await msg.ShowAsync();
            }
            catch (Exception ex)
            {
                var msg = new MessageDialog(ex.Message)
                {
                    Title = "Error"
                };

                await msg.ShowAsync();
            }
            finally
            {
                IsBusy = false;
            }
        }

        /// 
        /// Connects to the database. Closes the dialog and returns the connection string if successful.
        /// 
        
        /// 
        /// Reads the most recent connections from local settings.
        /// 
        private List ReadMostRecentConnections()
        {
            try
            {
                var localSettings = ApplicationData.Current.LocalSettings;
                var fullString = localSettings.Values["SqlConnectionDialogServers"].ToString();
                return fullString.Split("###").ToList();
            }
            catch (Exception)
            {
                // Probably corrupt settings.
            }

            return new List();
        }

        /// 
        /// Writes the most recent connections to local settings.
        /// 
        private void SaveMostRecentConnections()
        {
            try
            {
                var fullString = string.Join("###", mostRecentConnections);
                var localSettings = ApplicationData.Current.LocalSettings;
                localSettings.Values["SqlConnectionDialogServers"] = fullString;
            }
            catch (Exception)
            {
                // No need to crash the app for this.
            }
        }
    }
}

你可能感兴趣的:(UWP)