做一个简单WPF连接数据库的
控件类型和名称:
DataGrid:dataGrid
Button1 :Button1
Button :Button2
TextBox :txtuserName
在引用App.config写数据库的连接字符串
1
2
3
4
5
6
7
8
9
10
|
<? xml version = "1.0" encoding = "utf-8" ?> < configuration > < startup > < supportedRuntime version = "v4.0" sku = ".NETFramework,Version=v4.5" /> </ startup > < appSettings > <!--数据库连接字符串--> < add key = "ConnString" value = "Data Source=.;initial Catalog=educ; user=sa; Password=123456;Pooling=true" /> </ appSettings > </ configuration > |
<add key ="ConnString" value ="Data Source=.;initial Catalog=educ; user=sa; Password=123456;Pooling=true" />
Data Source=.表示本机,可以写ip地址 initial Catalog=数据库名 user=用户名 Password=密码;写一个DataBaseHelper的数据库类
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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
|
namespace _03连接数据库 { class DataBaseHelper { /// 数据库打开连接的方法 /// /// </ summary > /// < returns ></ returns > public static SqlConnection getSqlConnection() { SqlConnection sqlConnection = new SqlConnection(); try { //获取数据库字符串 sqlConnection.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnString"]; sqlConnection.Open(); sqlConnection.Close(); } catch { throw new Exception("无法连接数据库服务器"); } return sqlConnection; } /// sql增删改的方法 /// /// </ summary > /// < param name = "sqlstr" ></ param > /// < returns ></ returns > public static int GetNonQueryEffect(string sqlstr) { SqlConnection sqlConnection = new SqlConnection(); try { sqlConnection.Open(); //创建要执行的语句 SqlCommand cmd = new SqlCommand(sqlstr, sqlConnection); return cmd.ExecuteNonQuery();//返回执行语句中的错误 } catch (Exception ex) { throw new Exception(ex.ToString()); } finally { sqlConnection.Close(); sqlConnection.Dispose();//释放资源 } } /// 读取数据的的方法 /// /// </ summary > /// < param name = "sqlstr" ></ param > /// < returns ></ returns > public static DataSet GetDataset(string sqlstr) { SqlConnection conn = getSqlConnection(); try { conn.Open();//打开数据库连接 SqlDataAdapter sda = new SqlDataAdapter(sqlstr ,conn );//更新数据库的命令 DataSet ds = new DataSet(); sda.Fill(ds);//填充 return ds; } catch (Exception ex) { throw new Exception(ex.ToString ()); } finally { conn.Close(); conn.Dispose(); } } } } |
按键的代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
|
private void Button_Click_1(object sender, RoutedEventArgs e) { string str = "select *FROM student";//查询的语句 dataGrid.ItemsSource = DataBaseHelper.GetDataset(str).Tables[0].DefaultView; } private void Button_Click_2(object sender, RoutedEventArgs e) { if (txtuserName.Text.Trim()== " ") { return; } string strr = string.Format("select *FROM student where sname='{0}'", txtuserName.Text); dataGrid.ItemsSource = DataBaseHelper.GetDataset(strr).Tables[0].DefaultView; } |
以上这篇WPF简单的数据库查询实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持服务器之家。
原文链接:http://www.cnblogs.com/enduo/p/7793907.html