做一个简单WPF连接数据库的
控件类型和名称:DataGrid:dataGrid Button1 :Button1 Button: Button2 TextBox : txtuserName
在引用App.config写数据库的连接字符串
<?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 namespace _03连接数据库 2 { 3 class DataBaseHelper 4 { 5 6 /// 数据库打开连接的方法 7 /// 8 /// </summary> 9 /// <returns></returns> 10 public static SqlConnection getSqlConnection() 11 { 12 SqlConnection sqlConnection = new SqlConnection(); 13 try 14 { 15 //获取数据库字符串 16 sqlConnection.ConnectionString = System.Configuration.ConfigurationSettings.AppSettings["ConnString"]; 17 sqlConnection.Open(); 18 sqlConnection.Close(); 19 } 20 catch 21 { 22 23 throw new Exception("无法连接数据库服务器"); 24 } 25 26 return sqlConnection; 27 } 28 29 /// sql增删改的方法 30 /// 31 /// </summary> 32 /// <param name="sqlstr"></param> 33 /// <returns></returns> 34 public static int GetNonQueryEffect(string sqlstr) 35 { 36 SqlConnection sqlConnection = new SqlConnection(); 37 try 38 { 39 sqlConnection.Open(); 40 //创建要执行的语句 41 SqlCommand cmd = new SqlCommand(sqlstr, sqlConnection); 42 return cmd.ExecuteNonQuery();//返回执行语句中的错误 43 } 44 catch (Exception ex) 45 { 46 throw new Exception(ex.ToString()); 47 48 } 49 finally 50 { 51 sqlConnection.Close(); 52 sqlConnection.Dispose();//释放资源 53 } 54 55 } 56 57 /// 读取数据的的方法 58 /// 59 /// </summary> 60 /// <param name="sqlstr"></param> 61 /// <returns></returns> 62 public static DataSet GetDataset(string sqlstr) 63 { 64 SqlConnection conn = getSqlConnection(); 65 try 66 { 67 conn.Open();//打开数据库连接 68 SqlDataAdapter sda = new SqlDataAdapter(sqlstr ,conn );//更新数据库的命令 69 DataSet ds = new DataSet(); 70 sda.Fill(ds);//填充 71 return ds; 72 } 73 catch (Exception ex) 74 { 75 76 throw new Exception(ex.ToString ()); 77 } 78 finally 79 { 80 conn.Close(); 81 conn.Dispose(); 82 } 83 } 84 } 85 }
按键的代码
1 private void Button_Click_1(object sender, RoutedEventArgs e) 2 { 3 string str = "select *FROM student";//查询的语句 4 dataGrid.ItemsSource = DataBaseHelper.GetDataset(str).Tables[0].DefaultView; 5 6 } 7 private void Button_Click_2(object sender, RoutedEventArgs e) 8 { 9 if (txtuserName.Text.Trim()== " ") 10 { 11 return; 12 } 13 string strr = string.Format("select *FROM student where sname='{0}'", txtuserName.Text); 14 dataGrid.ItemsSource = DataBaseHelper.GetDataset(strr).Tables[0].DefaultView; 15 }