App.config
<?xml version="1.0" encoding="utf-8" ?> <configuration> <startup> <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" /> </startup> <connectionStrings> <add name="SampleDB" connectionString="Server=.;Database=myDataBase;User Id=myUsername;Password=myPassword;" providerName="System.Data.SqlClient"/> </connectionStrings> </configuration>
新建一个类
namespace WpfApp3 { public class DataAccess { //use name search public List<Person> GetPeople(string lastName) { using (IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("SampleDB"))) { //var output = connection.Query<Person>($"select * from people where lastname = '{ lastName }'").ToList(); var output = connection.Query<Person>($"dbo.People_Gotbylastname @lastname", new { LastName = lastName }).ToList(); return output; } } public void InsertPerson( string firstname,string lastname,string email ,string phone) { using(IDbConnection connection = new System.Data.SqlClient.SqlConnection(Helper.CnnVal("SampleDB"))) { //Person newPerson = new Person { FirstName = firstname, LastName = lastname, Email = email, PhoneNumber = phone } List<Person> people = new List<Person>(); people.Add(new Person { FirstName = firstname, LastName = lastname, Email = email, PhoneNumber = phone }); connection.Execute("dbo.People_insert @Firstname,@lastname,@Email,@phone",people); } } } }
namespace WpfApp3 { public static class Helper { public static string CnnVal(string name) { return ConfigurationManager.ConnectionStrings[name].ConnectionString; } } }
调用
namespace WpfApp3 { /// <summary> /// MainWindow.xaml 的交互逻辑 /// </summary> public partial class MainWindow : Window { List<Person> people = new List<Person>(); public MainWindow() { InitializeComponent(); //peopleFoundListbox.Datasource = people; peopleFoundListbox.DisplayMemberPath = "FullInfo"; } private void search_Click(object sender, RoutedEventArgs e) { DataAccess db = new DataAccess(); //people = db.GetPeople(lastNameText.Text); } } }