繁体   English   中英

清理 c# 代码连接到 SQL 数据库

[英]cleaning up c# code connecting to SQL databse

我在 Visual Studio 2019 中创建了一个表单,允许用户连接到我在 SQL 中创建的数据库。 它允许查找、编辑、删除和添加到名为项目的表中。

我只是想帮助清理这段代码,因为它感觉非常混乱,并且非常感谢任何指针来帮助将这段代码分成单独的类,以及我将如何 go 这样做。

using System;
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace FinalDatabaseConnection
{
public partial class Form1 : Form
{

    public Form1()
    {
        InitializeComponent();

    }

    //  `if statement dealing with SQL query selection decided through combo box`

    //if statment dealing with sql queries once button hit
    private void button1_Click(object sender, EventArgs e)
    {
        lblCompleteItemInfo.Text = ("");
        String source = @"Data Source=WIN10-LAP-HJP\MSSQLSERVER1;Initial Catalog=VisualStudioConnect;Integrated Security=True";
        SqlConnection con = new SqlConnection(source);
        con.Open();

        if ((string)cbfunctionSelection.SelectedItem == "Find" && checkBoxPCSearch.Checked)
        {

            String sqlSelectQuery = "SELECT * FROM Items Where PartCode = @SelectedPartCode";

            var cmd = new SqlCommand(sqlSelectQuery, con);

            SetInsertParameters(cmd);
            SqlDataReader dr = cmd.ExecuteReader();
            SetResponse(dr);
            AllVisible();

        }

        else if ((string)cbfunctionSelection.SelectedItem == "Find" && checkBoxNameSearch.Checked)
        {
            checkBoxPCSearch.Checked = false;
            String sqlSelectQuery = "SELECT * FROM Items Where Name = @SelectedName";

            var cmd = new SqlCommand(sqlSelectQuery, con);

            SetInsertParameters(cmd);
            SqlDataReader dr = cmd.ExecuteReader();
            SetResponse(dr);
            AllVisible();
        }


        if ((String)cbfunctionSelection.SelectedItem == "Add")
        {
            checkBoxNameSearch.Checked = false;
            var cmd = new SqlCommand(
                "INSERT INTO items(Description,Colour,Manufacturer,StockLevel,Name) " +
                "VALUES ( @Description, @Colour, @Manufacturer, @StockLevel,@Name)", con);
            SetInsertParameters(cmd);
            cmd.ExecuteReader();

        }
        else if ((string)cbfunctionSelection.SelectedItem == "Delete")
        {

            var sqlDeleteQuery = "Delete from items where PartCode =  @SelectedPartCode";
            SqlCommand cmd = new SqlCommand(sqlDeleteQuery, con);
            SetInsertParameters(cmd);
            SqlDataReader myreader;
            myreader = cmd.ExecuteReader();
            myreader.Read();
        }
        else if ((string)cbfunctionSelection.SelectedItem == "Edit")
        {

            var cmd = new SqlCommand("update items SET Description = @Description ,Colour 
= @Colour, Manufacturer = @Manufacturer, StockLevel = @StockLevel, Name = @Name where partcode = @SelectedPartCode", con);

            SetInsertParameters(cmd);
            cmd.ExecuteReader();
        }
        con.Close();
    }
    //setting the response for the find function


    private void SetResponse(SqlDataReader dr)
    {

        if (dr.Read())
        {

            string itemDescription = (dr["Description"].ToString());
            txtDescription.Text = (dr["Description"].ToString());

            string itemColour = (dr["Colour"].ToString());
            txtColour.Text = (dr["Colour"].ToString());

            string itemManufacturer = (dr["Manufacturer"].ToString());
            txtManufacturer.Text = (dr["Manufacturer"].ToString());

            string itemStockLevel = (dr["StockLevel"].ToString());
            txtStockLevel.Text = (dr["StockLevel"].ToString());

            string itemName = (dr["Name"].ToString());

            txtName.Text = (dr["Name"].ToString());

            string itemPartCode = (dr["PartCode"].ToString());
            txtPartCode.Text = (dr["PartCode"].ToString());

            lblCompleteItemInfo.Text = ($"The items description is: {itemDescription} " +
                                        $"The items colour is: {itemColour} " +
                                        $"The items Manufacturer is: {itemManufacturer} " +
                                        $"The Items Stock Level is :{itemStockLevel} " +
                                        $"The Items Name is: {itemName} " +
                                        $"The items PartCode is: {itemPartCode} ");
        }

        else
        {
            MessageBox.Show("error");

        }
    }
    //applying the values for sql queries through the input in tbox
    private void SetInsertParameters(SqlCommand cmd)
    {

        cmd.Parameters.AddWithValue("@Description", txtDescription.Text);
        cmd.Parameters.AddWithValue("@Colour", txtColour.Text);
        cmd.Parameters.AddWithValue("@Manufacturer", txtManufacturer.Text);
        cmd.Parameters.AddWithValue("@StockLevel", txtStockLevel.Text);
        cmd.Parameters.AddWithValue("@Name", txtName.Text);
        cmd.Parameters.AddWithValue("@PartCode", txtPartCode.Text);

        cmd.Parameters.AddWithValue("@SelectedPartCode", txtPartCodeEnter.Text);
        cmd.Parameters.AddWithValue("@SelectedName", txtNameEnter.Text);
    }

`method to make all things visible so that it can be customised down for specfic selection in combo box`

                private void AllVisible()
    {
        //txtboxes
        txtDescription.Visible = true;
        txtColour.Visible = true;
        txtManufacturer.Visible = true;
        txtStockLevel.Visible = true;
        txtName.Visible = true;
        txtPartCode.Visible = true;
        txtPartCodeEnter.Visible = true;
        txtNameEnter.Visible = true;
        //lbls  
        lblDescription.Visible = true;
        lblColour.Visible = true;
        lblManufacturer.Visible = true;
        lblStockLevel.Visible = true;
        lblName.Visible = true;
        lblPartCode.Visible = true;
        lblNameEnter.Visible = true;
        lblPartCode.Visible = true;
        checkBoxNameSearch.Visible = true;
        checkBoxPCSearch.Visible = true;
    }
        `Customising what is viewable depending on sql selection`

                private void cbfunctionSelection_SelectedIndexChanged(object sender, EventArgs e)
    {
        if ((String)cbfunctionSelection.SelectedItem == "Add")
        {
            AllVisible();

            checkBoxNameSearch.Visible = false;
            checkBoxPCSearch.Visible = false;

            txtPartCodeEnter.Visible = false;
            txtNameEnter.Visible = false;
            txtPartCode.Visible = false;

            lblPartCode.Visible = false;
            lblNameEnter.Visible = false;
            lblPartCode.Visible = false;

            HelpLabel.Text = ("input the details for the item to be added.");
        }
        else if ((String)cbfunctionSelection.SelectedItem == "Find")
        {
            AllVisible();
            txtDescription.Visible = false;
            txtColour.Visible = false;
            txtManufacturer.Visible = false;
            txtStockLevel.Visible = false;
            txtName.Visible = false;
            txtPartCode.Visible = false;

            lblDescription.Visible = false;
            lblColour.Visible = false;
            lblManufacturer.Visible = false;
            lblStockLevel.Visible = false;
            lblName.Visible = false;
            lblPartCode.Visible = false;

            HelpLabel.Text = ("input the Partcode of the item and the information will be displayed.");

        }
        else if ((String)cbfunctionSelection.SelectedItem == "Edit")
        {
            AllVisible();
            lblPartCode.Visible = false;
            txtPartCode.Visible = false;
            txtNameEnter.Visible = false;
            lblNameEnter.Visible = false;
            checkBoxNameSearch.Visible = false;
            checkBoxPCSearch.Visible = false;
            HelpLabel.Text = ("Input the partcode of the item you would like to edit. Then the Information.");
        }
        else if ((String)cbfunctionSelection.SelectedItem == "Delete")
        {
            AllVisible();
            txtDescription.Visible = false;
            txtColour.Visible = false;
            txtManufacturer.Visible = false;
            txtStockLevel.Visible = false;
            txtName.Visible = false;
            txtPartCode.Visible = false;
            txtNameEnter.Visible = false;
            checkBoxNameSearch.Visible = false;
            checkBoxPCSearch.Visible = false;

            lblDescription.Visible = false;
            lblColour.Visible = false;
            lblManufacturer.Visible = false;
            lblStockLevel.Visible = false;
            lblName.Visible = false;
            lblPartCode.Visible = false;
            lblNameEnter.Visible = false;
            HelpLabel.Text = ("Input the partcode of the item you would like to delete.");
        }
    }

    private void button1_Click_1(object sender, EventArgs e)
    {
        btnDisplayItemTable.Text = ("Refresh items table");
        //This is database connection string
        String source = @"Data Source=WIN10-LAP-HJP\MSSQLSERVER1;Initial Catalog=VisualStudioConnect;Integrated Security=True";

        //this is defining source as variable "con" to be used for SQL connection
        SqlConnection con = new SqlConnection(source);

        //opens connection
        con.Open();
        // just message box
        MessageBox.Show("connected");

        SqlDataAdapter sqlDa = new SqlDataAdapter("Select * From Items", source);
        DataTable dtb1 = new DataTable();
        sqlDa.Fill(dtb1);

        dgv1.DataSource = dtb1;
    }

    private void radioButton2_CheckedChanged(object sender, EventArgs e)
    {

    }

    private void button1_Click_2(object sender, EventArgs e)
    {
        new Form3().Show();
    }
}
}

As per ideal OOP You need to move your DB logic to seperate DB helper class rather than putting whole sets of logic to code behind of your windows Forms.

例如 SetInsertParameters 用于纯 DB 操作,可以在 DB 助手 class 中。

表单不应该负责存储数据库连接字符串,从 SQL 等获取数据...

您可以为几个常见的 DB 操作创建通用方法,这些操作将采用参数并会做一些必要的事情,例如下面的行可以 go 作为 DB 助手 class 中的常见 function

SetInsertParameters(cmd);
SqlDataReader dr = cmd.ExecuteReader();
SetResponse(dr);

此外,非 DB Helper 相关的公共逻辑也可以是公共 function 的一部分,可能在相同的形式代码后面或其他帮助器 class 中。

来自 Helper class 的 SetResponse 方法应返回 Modal class 以及描述、颜色、制造等所有属性。

因此,您可以从 Helper class 返回 Modal class 以及 Form.cs 中的所有属性,您可以在其中将所有这些属性与文本和 Label 控件等表单控件绑定。

这样你的 UI 和 DB 层就会解耦,表单不会有任何 DB 的引用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM