Go homepage(回首页)
Upload pictures (上传图片)
Write articles (发文字帖)

The author:(作者)qq
published in(发表于) 2014/7/9 1:35:03
ADO.NET删除数据库中数据

ADO.NET删除数据库中数据

删除数据库中数据

通过SqlCommand类的CommandText方法(为其构造delete语句)与ExecuteNonQuery实现删除表中数据的功能,程序运行结果如图1、图2和图3所示。



图1 提示窗体



图2 删除信息窗体



图3 提示窗体

程序开发步骤如下。

(1)新建一个windows窗体(FrmDelete),在窗体上添加相应的控件(如图2所示)。

(2)在(ClsDBControl.cs)类内完成向数据库中删除数据的方法DeleteDB。

(3)主要程序代码如下。

首先实例化一个SqlCommand对象(cmd),然后通过参数sql(SQL 语句)来构建cmd对象,最后通过cmd对象的ExecuteNonQuery方法执行SQL语句,实现代码如下。

public bool DeleteDB (String sql)

{

using (SqlCommand cmd = new SqlCommand())

{

try

{

cmd.CommandText = sql;//设置SQL语句

cmd.Connection = ConDB();//调用打开数据库连接方法

cmd.ExecuteNonQuery();//执行

return True;

}

catch

{

return False;

}

}

}

单击【删除信息】按钮,将构造一条SQL语句(实现删除指定信息的功能),然后将这条语句传给deleteDB方法,实现数据的删除,实现代码如下。

private void button1_Click(object sender, EventArgs e)

{

if (this.textBox1.Text.Trim().ToString() != "")

{

ClsDB.ClsDBControl DBC = new OptDB.ClsDB.ClsDBControl();

string strSql = "delete from t_people where tb_PID='" +

this.textBox1.Text.Trim().ToString() + "'";

if (DBC.deleteDB(strSql))

{

MessageBox.Show("OK");

}

}

else

{

MessageBox.Show("请输入编号信息");

}

}

注意:操作添加、修改、删除的方法实质是一样的,只是名称不同。

完整程序代码如下:

★ ★★★★FrmDelete.cs窗体代码文件完整程序代码★★★★★

using System;

using System.Collections.Generic;

using System.ComponentModel;

using System.Data;

using System.Drawing;

using System.Text;

using System.Windows.Forms;

namespace OptDB

{

public partial class FrmDelete : Form

{

public FrmDelete()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

if (this.textBox1.Text.Trim().ToString() != "")

{

ClsDB.ClsDBControl DBC = new OptDB.ClsDB.ClsDBControl();

string strSql = "delete from t_people where tb_PID='" + this.textBox1.Text.Trim().ToString() + "'";

if (DBC.DeleteDB(strSql))

{

MessageBox.Show("OK");

}

}

else

{

MessageBox.Show("请输入编号信息");

}

}

}

}

★ ★★★★FrmDelete.designer.cs窗体设计文件完整程序代码★★★★★

namespace OptDB

{

partial class FrmDelete

{

///



/// 必需的设计器变量。

///


private System.ComponentModel.IContainer components = null;

///

/// 清理所有正在使用的资源。

///


/// 如果应释放托管资源,为 true;否则为 false。

protected override void Dispose(bool disposing)

{

if (disposing && (components != null))

{

components.Dispose();

}

base.Dispose(disposing);

}

#region Windows 窗体设计器生成的代码

///

/// 设计器支持所需的方法 - 不要

/// 使用代码编辑器修改此方法的内容。

///


private void InitializeComponent()

{

this.textBox1 = new System.Windows.Forms.TextBox();

this.label1 = new System.Windows.Forms.Label();

this.button1 = new System.Windows.Forms.Button();

this.SuspendLayout();

//

// textBox1

//

this.textBox1.Location = new System.Drawing.Point(65, 16);

this.textBox1.Name = "textBox1";


If you have any requirements, please contact webmaster。(如果有什么要求,请联系站长)





QQ:154298438
QQ:417480759