简体   繁体   English

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

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

I'm learning database connectivity using C# Windows Form Application in Visual Studio and SQL Server Management Studio.我正在使用 Visual Studio 中的 C# Windows Form Application 和 SQL Server Management Studio 学习数据库连接。

The problem I'm having is I'm unable to access the AddParams() and sqlQueryCmd() functions from the SQLConn.cs Class.我遇到的问题是我无法从SQLConn.cs Class 访问AddParams()sqlQueryCmd()函数。 I've tried changing the access modifiers from private to public but it didn't work.我尝试将访问修饰符从私有更改为公共,但没有奏效。 Can anyone guide me here?有人可以在这里指导我吗? I don't know what I'm doing wrong.我不知道我做错了什么。

SQLConn.cs 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 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**
        }
    }
}

As people in the comments stated, you'll have to move the functions out of Main1.正如评论中的人所说,您必须将功能移出 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 method/function would not solve the problem since the SqlParam variable is not available in sqlConn class. Movint addParam 方法/函数无法解决问题,因为 SqlParam 变量在 sqlConn class 中不可用。 the better approach for your goal is to to this:实现目标的更好方法是:

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();
                }
            }
        }
    }
    
}

} }

in this scenario there is no need for Main method since every application can have only one Main method and winForms by default already have one Main method.在这种情况下,不需要 Main 方法,因为每个应用程序只能有一个 Main 方法,而 winForms 默认情况下已经有一个 Main 方法。

secondly, the SQLConn class can have private field of type List, and a public method called AddParam which its responsibility is to add new params to it.其次,SQLConn class 可以具有 List 类型的私有字段,以及一个名为 AddParam 的公共方法,其职责是向其添加新参数。

Lastly, a public SqlQueryCmd method is added to do the rest of the job.最后,添加了一个公共 SqlQueryCmd 方法来执行作业的 rest。

you can now use this class to execute your query like this:您现在可以使用此 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.

相关问题 无法从C#中的客户端(控制台应用程序)通过WCF服务(已通过Windows身份验证)访问SQL Server - Unable to access SQL Server from WCF service (Windows authenticated) from client (console application) in C# 从C#文件夹中使用特定的服务器名称打开.sql文件SQL Server Management Studio - Open .sql file SQL Server Management Studio from a folder throught C# with a specfic server name 使用C#应用程序远程访问使用SQL Server 2014 Management Studio创建的数据库 - Remote access using C# application to database created using SQL Server 2014 Management Studio 使用C#从Visual Studio中的其他表单访问变量 - Access variable from another form in Visual Studio with c# SQL无法在C#上运行,但可以在SQL Server Management Studio中运行 - SQL not working on c# but working in SQL Server Management Studio C#无法从另一个类更改窗体的组件 - C# Unable To Change Components Of Form From Another Class 从C#运行时,SQL查询超时,在SQL Server Management Studio中快速 - SQL query times out when run from C#, fast in SQL Server Management Studio 无法从以前的Windows窗体访问Class方法-C# - Cannot access Class methods from previous windows form - C# 无法从Windows应用程序C#连接到SQL Server数据库 - unable to connect to sql server database from windows application c# 如何从Windows窗体中的另一个类修改PictureBox? C# - How to modify a PictureBox from another class in Windows Form? C#
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM