首页 > 编程 > C# > 正文

WPF简单的数据库查询实例

2020-01-24 00:24:51
字体:
来源:转载
供稿:网友

 做一个简单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的数据库类

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(); } }  }}

按键的代码

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简单的数据库查询实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表