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

The author:(作者)qq
published in(发表于) 2014/7/9 1:34:59
ADO.NET修改数据库中数据

ADO.NET修改数据库中数据

修改数据库中数据

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



图1 提示窗体



图2修改信息窗体



图3 提示窗体

程序开发步骤如下。

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

(2)在(ClsDBControl.cs)类内完成修改数据库中数据的方法UpdateDB。

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

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

public bool updateDB (String sql)

{

using (SqlCommand cmd = new SqlCommand())

{

try

{

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

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

cmd.ExecuteNonQuery();//执行

return True;

}

catch

{

return False;

}

}

}

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

private void button1_Click(object sender, EventArgs e)

{

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

{

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

string strSql = "update t_people set tb_psex='" + this.textBox3.Text.Trim().ToString() +

"',tb_pname= '" + this.textBox2.Text.Trim().ToString() + "' where tb_PID='" +

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

if (DBC.updateDB(strSql))

{

MessageBox.Show("OK");

}

}

else

{

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

}

}

注意:思想要严密,例如,在修改时要确保编号信息不为空,最好的方法是先验证是否存在要更改的编号,这样可以使程序更严谨。

完整程序代码如下:

★ ★★★★FrmUpdate.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 FrmUpdate : Form

{

public FrmUpdate()

{

InitializeComponent();

}

private void button1_Click(object sender, EventArgs e)

{

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

{

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

string strSql = "update t_people set tb_psex='" + this.textBox3.Text.Trim().ToString() + "',tb_pname= '" + this.textBox2.Text.Trim().ToString() + "' where tb_PID='" + this.textBox1.Text.Trim().ToString() + "'";

if (DBC.updateDB(strSql))

{

MessageBox.Show("OK");

}

}

else

{

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

}

}

}

}

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

namespace OptDB

{

partial class FrmUpdate

{

///



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

///


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.textBox3 = new System.Windows.Forms.TextBox();


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





QQ:154298438
QQ:417480759