ADO.NET添加新数据

通过ADO.NET中的Command对象可以向数据库发送操作命令,这些操作命令可以是某个SQL语句或存储过程。通常对数据库的操作包括增加、删除、修改和查询4种。前3种是单向的,即这些操作修改数据库中数据后并不返回数据。查询属于双向操作,既要向数据库提交查询命令,还要从数据库中获取数据。

注意:所有单向操作都使用Command对象的ExecuteNonQuery()方法执行。

我们接着打开School,在Form1窗体中添加“学生管理”按钮。设置其Name属性为“btnManage”。



为“学生管理”按钮添加代码:

        private void btnStuManage_Click(object sender, EventArgs e)
        {
            frmStudentManage stu = new frmStudentManage();
            stu.Show();
        }

右击解决方案面板中的项目名称,选择添加——Windows窗体命令,打开“添加新项”对话框,选择“Windows”选项,然后修改名称为“frmStudentMange”。

设计窗体frmStudentManage如下:

其中表示学号,姓名,性别,年龄,班级的五个Label控件,Name属性更改与否,关系不大。三个文本框TextBox的Name属性分别更改为:学号txtId,姓名txtName,年龄txtAge,性别和班级添加组合框。其中性别组合框中项的值为男和女,班级组合框项的值自己设计好了,Name属性分别设置为cboSex和cboClass。下面的四下按钮,分别设置Name属性:添加btnAdd,删除btnDelete,更新btnModify,退出btnExit。

Sql server的表设计在此我就不多说了,要有相应的字段对应。

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;

namespace School
{
    public partial class frmStudentManage : Form
    {
        public frmStudentManage()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            this.txtId.Enabled = false;
            this.btnDelete.Enabled = false;
            this.btnModify.Enabled = false;

        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            string strcon = @"data source=.\sqlexpress;initial catalog=School;uid=sa;pwd=123456";
            SqlConnection con = new SqlConnection(strcon);
            string sql = "insert into Student values('" + this.txtName.Text.Trim() + "','" + this.cboSex.Text + "'," + Convert.ToInt32(this.txtAge.Text) + ",'" + this.cboClass.Text + "')";
            SqlCommand comm = new SqlCommand(sql, con);
            try
            {
                con.Open();
                if (comm.ExecuteNonQuery() > 0)
                {
                    MessageBox.Show("添加成功");
                    this.btnDelete.Enabled = true;
                    this.btnModify.Enabled = true;
                }
                else
                {
                    MessageBox.Show("添加失败");
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);

            }
            finally
            {
                con.Close();

            }
        }

        private void btnExit_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值