C#连接Sql实现注册用户窗体的两种方式

版权声明:转载原创文章请以超链接形式请注明原文章出处,尊重作者,尊重原创!


恰饭广告




方法1:(参数化sql语句)

主要代码:

 string stuID = this.textBox1.Text.Trim();
            string stuName = this.textBox2.Text.Trim();
            string stuSex = this.radioButton1.Checked ? "男" : "女";
            string testDB = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString;
            SqlConnection conn = new SqlConnection(testDB);
            try {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from T_StuInfo where StuID = @StuID";
            cmd.Parameters.AddWithValue("@StuID", stuID);
            cmd.Parameters.AddWithValue("@StuName", stuName);
            cmd.Parameters.AddWithValue("@StuSex", stuSex);
            SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    //判断读取到的数据库中的学号与输入的学号是否相同
                    if (reader["StuID"].ToString() == stuID)
                    {
                        MessageBox.Show("学号已存在");
                        this.textBox1.Focus();
                        this.textBox1.SelectAll();
                    }
                    //关闭读取器
                    reader.Close();
                }
                else
                {
                    //关闭读取器
                    reader.Close();
                    cmd.CommandText = "insert into T_StuInfo values(@StuID, @StuName, @StuSex)";
                    //获取执行sql语句后受影响的行数
                    int rowCount = cmd.ExecuteNonQuery();
                    if (rowCount == 1) //Update、Insert和Delete返回1,其他返回-1
                    {
                        MessageBox.Show("学生【" + this.textBox1.Text + "】录入成功!");
                        this.textBox1.Text = "";
                        this.textBox2.Text = "";
                        reader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }

方法2:(调用存储过程)

sql创建储存过程语句:

--返回-1代表学号已经存在,1代表插入成功,0代表插入异常
create proc up_addStu
@stuId varchar(10),@stuName varchar(10),@sex varchar(2)
as
 declare @count int
 select @count = COUNT(*) from T_StuInfo where StuID = @stuId
 if @count = 1
 begin
  return -1
 end
 else
 begin
   insert into T_StuInfo values(@stuId,@stuName,@sex)
   if @@ROWCOUNT = 1 --返回插入的结果数量
   begin
   return 1
   end
   else
   begin
    return 0
   end
 end

c#主要代码:

string stuID = this.textBox1.Text.Trim();
            string stuName = this.textBox2.Text.Trim();
            string stuSex = this.radioButton1.Checked ? "男" : "女";
            string testDB = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString;
            SqlConnection conn = new SqlConnection(testDB);
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("up_addStu", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                //定义参数的值
                cmd.Parameters.AddWithValue("@StuID", stuID);
                cmd.Parameters.AddWithValue("@StuName", stuName);
                cmd.Parameters.AddWithValue("@sex", stuSex);
                //添加返回值参数
                SqlParameter count = cmd.Parameters.Add("@count", SqlDbType.Int);
                count.Direction = ParameterDirection.ReturnValue;
                cmd.ExecuteNonQuery(); //Update、Insert和Delete返回1 ,其他返回-1
                int i = int.Parse(cmd.Parameters["@count"].Value.ToString());
                if (i == -1)
                {
                    MessageBox.Show("学号已存在");
                    this.textBox1.Focus();
                    this.textBox1.SelectAll();
                }
                else if (i == 1)
                {
                    MessageBox.Show("学生【" + this.textBox1.Text + "】录入成功!");
                }
                else
                {
                    MessageBox.Show("添加失败");
                    this.textBox1.Focus();
                    this.textBox1.SelectAll();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }

UI界面实现

注册窗体界面

SQL Server表结构

注册窗体数据库的表结构

Form1.cs代码:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
using System.Configuration;
namespace RegUser
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            string stuID = this.textBox1.Text.Trim();
            string stuName = this.textBox2.Text.Trim();
            string stuSex = this.radioButton1.Checked ? "男" : "女";
            string testDB = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString;
            SqlConnection conn = new SqlConnection(testDB);
            try {
            conn.Open();
            SqlCommand cmd = conn.CreateCommand();
            cmd.CommandText = "select * from T_StuInfo where StuID = @StuID";
            cmd.Parameters.AddWithValue("@StuID", stuID);
            cmd.Parameters.AddWithValue("@StuName", stuName);
            cmd.Parameters.AddWithValue("@StuSex", stuSex);
            SqlDataReader reader = cmd.ExecuteReader();
                if (reader.Read())
                {
                    //判断读取到的数据库中的学号与输入的学号是否相同
                    if (reader["StuID"].ToString() == stuID)
                    {
                        MessageBox.Show("学号已存在");
                        this.textBox1.Focus();
                        this.textBox1.SelectAll();
                    }
                    //关闭读取器
                    reader.Close();
                }
                else
                {
                    //关闭读取器
                    reader.Close();
                    cmd.CommandText = "insert into T_StuInfo values(@StuID, @StuName, @StuSex)";
                    //获取执行sql语句后受影响的行数
                    int rowCount = cmd.ExecuteNonQuery();
                    if (rowCount == 1) //Update、Insert和Delete返回1,其他返回-1
                    {
                        MessageBox.Show("学生【" + this.textBox2.Text + "】录入成功!");
                        reader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
        private void button2_Click(object sender, EventArgs e)
        {
            string stuID = this.textBox1.Text.Trim();
            string stuName = this.textBox2.Text.Trim();
            string stuSex = this.radioButton1.Checked ? "男" : "女";
            string testDB = ConfigurationManager.ConnectionStrings["testDB"].ConnectionString;
            SqlConnection conn = new SqlConnection(testDB);
            try
            {
                conn.Open();
                SqlCommand cmd = new SqlCommand("up_addStu", conn);
                cmd.CommandType = CommandType.StoredProcedure;
                //定义参数的值
                cmd.Parameters.AddWithValue("@StuID", stuID);
                cmd.Parameters.AddWithValue("@StuName", stuName);
                cmd.Parameters.AddWithValue("@sex", stuSex);
                //添加返回值参数
                SqlParameter count = cmd.Parameters.Add("@count", SqlDbType.Int);
                count.Direction = ParameterDirection.ReturnValue;
                cmd.ExecuteNonQuery(); //Update、Insert和Delete返回1 ,其他返回-1
                int i = int.Parse(cmd.Parameters["@count"].Value.ToString());
                if (i == -1)
                {
                    MessageBox.Show("学号已存在");
                    this.textBox1.Focus();
                    this.textBox1.SelectAll();
                }
                else if (i == 1)
                {
                    MessageBox.Show("学生【" + this.textBox2.Text + "】录入成功!");
                }
                else
                {
                    MessageBox.Show("添加失败");
                    this.textBox1.Focus();
                    this.textBox1.SelectAll();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            finally
            {
                conn.Close();
                conn.Dispose();
            }
        }
    }
}

GitHub源码下载:https://github.com/kiritobin/RegUserTowWay

原文链接:https://www.idaobin.com/archives/1051.html

让我恰个饭吧.ヘ( ̄ω ̄ヘ)

支付宝 ——————- 微信
图片加载中图片加载中



恰饭广告

发表评论

您的电子邮箱地址不会被公开。 必填项已用*标注

× 9 = 54