2 u010020553 u010020553 于 2013.09.22 19:15 提问

ExecuteNonQuery() 返回值为0

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 UpdateTest
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}

    bool CheckInfo()
    {
        if (this.txtUserSex.Text.Trim() == "")
        {
            MessageBox.Show ("学号不能为空");
            return false;
        }
        else if (this.txtUserName.Text.Trim() == "")
        {
            MessageBox.Show("姓名不能为空");
            return false;
        }
        return true;

    }

    private void button1_Click(object sender, EventArgs e)
    {
        if (CheckInfo())
        {
            string userSex=this.txtUserSex.Text.Trim();
            string userName=this.txtUserName.Text.Trim();
            string cnnString = "data source=(local);database=CTestDB;Integrated Security=true";
            SqlConnection cnn = new SqlConnection(cnnString);
            String sqlStr = "update Student set Stu_sex='" + userSex + "'" + "where Stu_name='" + userName + "'";
            cnn.Open();
            SqlCommand cmd = new SqlCommand(sqlStr, cnn);
            int RecordsAffected = cmd.ExecuteNonQuery();
            cnn.Close();
            MessageBox.Show("更新数据位" + RecordsAffected);

        }
    }

    private void button2_Click(object sender, EventArgs e)
    {
        if (CheckInfo())
        {
            string userSex= this.txtUserSex.Text.Trim();
            string userName = this.txtUserName.Text.Trim();
            string cnnString = "data source=(local);database=CTestDB;Integrated Security=true";
            string sqlStr = "update Student set Stu_sex=@userSex where Stu_name=@userName";
            SqlConnection cnn = new SqlConnection(cnnString);
            SqlCommand cmd = new SqlCommand(sqlStr, cnn);
            cmd.Parameters.Add(new SqlParameter("@userSex", userSex));
            cmd.Parameters.Add(new SqlParameter("@userName", userName));
            cnn.Open();
            int RecordAffected = cmd.ExecuteNonQuery();
            cnn.Close();
            MessageBox.Show("更新数据为" + RecordAffected);
        }
    }
}

}

1个回答

xhk24
xhk24   2013.09.30 13:47

你SELECT下表看看 Stu_name=@userName有没有查询结果

Csdn user default icon
上传中...
上传图片
插入图片
准确详细的回答,更有利于被提问者采纳,从而获得C币。复制、灌水、广告等回答会被删除,是时候展现真正的技术了!