博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
笔记6:winfrom连接sql server 进行数据交换
阅读量:7062 次
发布时间:2019-06-28

本文共 1914 字,大约阅读时间需要 6 分钟。

今天的作业是用winfrom窗体做一个留言板,如图:

  

  要求和数据库有查询和添加功能。下拉框里的值是直接获取数据库中的值

一、连接数据库,获取表中数据

1         //创建一个存数据的表 2             DataTable table = new DataTable(); 3             string liuyanConn = "server=.;integrated security=true;database=DataGridView"; 4             string liuyanSql = "select UserName as 用户名 ,Content as 留言内容 from UserInfo"+  //两张表联合查询                       +" inner join MessageInfo on MessageInfo.UserId=UserInfo.UserId"; 5             SqlConnection sqlConn = new SqlConnection(liuyanConn); 6             SqlCommand sqlComm = new SqlCommand(liuyanSql, sqlConn); 7  8             SqlDataAdapter da = new SqlDataAdapter(sqlComm); 9             da.Fill(table);10             this.dataGridView1.DataSource = table;

二、获取数据库中的用户名,并赋值到下拉列表中

1          //下拉菜单 2             string liuyanSql2 = "select * from UserInfo"; 3             sqlConn.Open(); 4             SqlCommand command = new SqlCommand(liuyanSql2, sqlConn); 5             SqlDataReader reader = command.ExecuteReader(); 6             while (reader.Read()) 7             { 8                 string name = (String)reader["UserName"]; 9                 this.comboBox1.Items.Add(name);10             }11             sqlConn.Close();

三、将选的留言对象和留言内容存到数据库中,然后更新界面

//添加留言            SqlConnection sqlConn2 = new SqlConnection(liuyanConn);            sqlConn2.Open();            string liuyanSql2 = string.Format("insert into MessageInfo(Content,UserId) values ('{0}',{1})",this.textBox1.Text, id);            SqlCommand command2 = new SqlCommand(liuyanSql2, sqlConn2);            int i = command2.ExecuteNonQuery();            sqlConn2.Close();            if (i > 0)            {                MessageBox.Show("留言成功!");            }            xianshi();

  难点:1、将数据库中的值取出来,然后赋值到下拉列表中

     2、用户信息和留言内容不是一个表,由外键相连着

        因此需要根据表1中的用户名查询到用户编号,然后再将用户编号和留言内容存到表2中

      這就多涉及一次查询,插入

    ps:這次代码写得相当的啰嗦,慢慢再改吧

转载于:https://www.cnblogs.com/gx-143/p/5388829.html

你可能感兴趣的文章
解决开启服务器防火墙导致ftp不能连接的问题
查看>>
程序员网站
查看>>
p2v-VMware vCenter Converter Standalone 5.0
查看>>
在Windows平台上绿色安装postgresQL
查看>>
POJ 3617 Best Cow Line(贪心 字典序最小)
查看>>
oracle表中某个字段含有字符回车、空格的手动修改方式
查看>>
常用数学符号大全
查看>>
NGUI 学习笔记实战之二——商城数据绑定(Ndata)
查看>>
无法使用SQL Server Management Studio的找到Network Server
查看>>
kafka 遇到的错
查看>>
GIL - global interpreter lock
查看>>
MySQL笔记-最简单的方法来解决找不到mysqld.sock文件的问题
查看>>
securecrt中文乱码
查看>>
[转]Android获取、设置铃声,音量,静音,扬声器
查看>>
放大器(或集线器)模式(Hub)
查看>>
Web Part的Scope问题
查看>>
ToDoList
查看>>
在idea下两个项目之间的maven父子级项目依赖
查看>>
关于 js 对象 转 字符串 和 深拷贝 的探讨
查看>>
智能识别收货地址 javascript
查看>>