WPF简单的数据库查询实例
程序员文章站
2023-12-15 17:01:16
做一个简单wpf连接数据库的
控件类型和名称:
datagrid:datagrid  ...
做一个简单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简单的数据库查询实例就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持。