繁体   English   中英

无法从另一个 class 访问函数(C# Windows 表单,SQL Server Management Studio)

[英]Unable to access functions from another class (C# Windows Form, SQL Server Management Studio)

我正在使用 Visual Studio 中的 C# Windows Form Application 和 SQL Server Management Studio 学习数据库连接。

我遇到的问题是我无法从SQLConn.cs Class 访问AddParams()sqlQueryCmd()函数。 我尝试将访问修饰符从私有更改为公共,但没有奏效。 有人可以在这里指导我吗? 我不知道我做错了什么。

SQLConn.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Microsoft.Data.SqlClient;

namespace dbConnectivityTest1
{
    public class SQLConn
    {
        public static void Main1(string[] args)
        {
            using (SqlConnection connString = new SqlConnection("Server=ServerName;Database=DatabaseName;User Id=UserID;\r\nPassword=Password;"))
            {
                List<SqlParameter> paramList = new List<SqlParameter>();
                string AddParams(string tableName, object insVal)
                {
                    SqlParameter sqlparams = new SqlParameter(tableName, insVal);
                    paramList.Add(sqlparams);
                }
                SqlCommand sqlCmd = new SqlCommand();

                string sqlQueryCmd(string sqlQuery)
                {
                    int recordCount = 0;
                    string excptnShow = "";

                    try
                    {
                        connString.Open();
                        SqlCommand sqlCmd = new SqlCommand(sqlQuery, connString);
                        paramList.ForEach(p => { sqlCmd.Parameters.Add(p); });
                        paramList.Clear();
                        DataTable sqlDT = new DataTable();
                        SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
                        recordCount = sqlDA.Fill(sqlDT);
                    }
                    catch(Exception ex)
                    {
                        excptnShow = "Error: \r\n" + ex.Message;
                    }
                    finally
                    {
                        if (connString.State == ConnectionState.Open)
                        {
                            connString.Close();
                        }
                    }
                }
            }
        }
    }
}

Form1.cs

namespace dbConnectivityTest1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private SQLConn sqlDB = new SQLConn();

        private void enterNametextBox_Click(object sender, EventArgs e)
        {
            enterNametextBox.Clear();
        }

        private void submitButton_Click(object sender, EventArgs e)
        {
            while(fullNameTextBox.Text.Length <= 0)
            {
                MessageBox.Show("Please enter your Full Name!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            while(contactTextBox.Text.Length <= 0)
            {
                MessageBox.Show("Please enter your Contact Number!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            while(ageTextBox.Text.Length <= 0)
            {
                MessageBox.Show("Please enter your Age!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            while(emailTextBox.Text.Length <= 0)
            {
                MessageBox.Show("Please enter your E-mail!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            System.Text.RegularExpressions.Regex emailRegex = new System.Text.RegularExpressions.Regex(@"^[a-zA-Z0-9+_.-]+@[a-zA-Z0-9.-]+$");
            while(!emailRegex.IsMatch(emailTextBox.Text))
            {
                MessageBox.Show("Please enter a valid E-mail!", "Caption", MessageBoxButtons.OKCancel, MessageBoxIcon.Exclamation);
            }
            InsVal();
        }

        public void InsVal()
        {
            **I am trying to call the SQLConn.cs Functions here**
        }
    }
}

正如评论中的人所说,您必须将功能移出 Main1。

sing System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Microsoft.Data.SqlClient;

namespace dbConnectivityTest1
{
    public class SQLConn
    {
        public string AddParams(string tableName, object insVal)
        {
                SqlParameter sqlparams = new SqlParameter(tableName, insVal);
                paramList.Add(sqlparams);
        }

        public string sqlQueryCmd(string sqlQuery)
        {
                int recordCount = 0;
                string excptnShow = "";
                try
                {
                    connString.Open();
                    SqlCommand sqlCmd = new SqlCommand(sqlQuery, connString)
                    paramList.ForEach(p => { sqlCmd.Parameters.Add(p); });
                    paramList.Clear();
                    DataTable sqlDT = new DataTable();
                    SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
                    recordCount = sqlDA.Fill(sqlDT);
                }
                catch(Exception ex)
                {
                    excptnShow = "Error: \r\n" + ex.Message;
                }
                finally
                {
                    if (connString.State == ConnectionState.Open)
                    {
                        connString.Close();
                    }
                }
        }

        public static void Main1(string[] args)
        {
            using (SqlConnection connString = new SqlConnection("Server=ServerName;Database=DatabaseName;User Id=UserID;\r\nPassword=Password;"))
            {
                List<SqlParameter> paramList = new List<SqlParameter>();
                
                SqlCommand sqlCmd = new SqlCommand();
            }
        }
    }
}

Movint addParam 方法/函数无法解决问题,因为 SqlParam 变量在 sqlConn class 中不可用。 实现目标的更好方法是:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;

namespace dbConnectivityTest1
{
public class SQLConn
{

    private readonly string _connectionString;
    private List<SqlParameter> _paramList;
    public SQLConn()
    {
        _connectionString="Server=ServerName;Database=DatabaseName;User Id=UserID;\r\nPassword=Password;";
        _paramList = new List<SqlParameter>();
    }

    public void AddParams(string tableName, object insVal)
    {
        SqlParameter sqlparams = new SqlParameter(tableName, insVal);
        _paramList.Add(sqlparams);
    }

    public void sqlQueryCmd(string sqlQuery)
    {
        using (var sqlConn = new SqlConnection(_connectionString))
        {

            int recordCount = 0;
            string excptnShow = "";

            try
            {
                sqlConn.Open();
                SqlCommand sqlCmd = new SqlCommand(sqlQuery, sqlConn);
                _paramList.ForEach(p => { sqlCmd.Parameters.Add(p); });
                _paramList.Clear();
                DataTable sqlDT = new DataTable();
                SqlDataAdapter sqlDA = new SqlDataAdapter(sqlCmd);
                recordCount = sqlDA.Fill(sqlDT);
            }
            catch (Exception ex)
            {
                excptnShow = "Error: \r\n" + ex.Message;
            }
            finally
            {
                if (sqlConn.State == ConnectionState.Open)
                {
                    sqlConn.Close();
                }
            }
        }
    }
    
}

}

在这种情况下,不需要 Main 方法,因为每个应用程序只能有一个 Main 方法,而 winForms 默认情况下已经有一个 Main 方法。

其次,SQLConn class 可以具有 List 类型的私有字段,以及一个名为 AddParam 的公共方法,其职责是向其添加新参数。

最后,添加了一个公共 SqlQueryCmd 方法来执行作业的 rest。

您现在可以使用此 class 执行您的查询,如下所示:

private void button1_Click(object sender, EventArgs e)
    {
        var sqlConn = new SQLConn();

        sqlConn.AddParams("tableName","your Object");
        sqlConn.AddParams("tableName","your Object");
        sqlConn.AddParams("tableName","your Object");

        sqlConn.sqlQueryCmd("Query");
    }

暂无
暂无

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

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