如何使类中的方法返回消息 [英] How to make a method in class return a message

查看:64
本文介绍了如何使类中的方法返回消息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

IN C#

我有一个类可以通过向此方法发送一些参数来从数据库表中进行选择

发生错误时我想收到一条消息。 />


我做了这个类,但为了保存错误信息,我做了一个REF变量!



任何其他方式用正常变量或任何新方法替换Ref变量



我尝试过:



IN C#
I have a class to select from database table by sending some parameter to this method
when an error occurs I want to receive a message.

I made this Class but to save an error message I made a REF variable!

any other way to replace Ref variable with normal variable or any new methods

What I have tried:

public class DataManager
    {

        public bool SelectFromTable(ref string SQLErr, SqlConnection cnn, string 
                                    SQLString, DataSet ds, string dataTabelName)
        {
            try
            {
               
                SqlDataAdapter da = new SqlDataAdapter(@"Select " + SQLString, cnn);
               
                da.Fill(ds, dataTabelName);

                if (ds.Tables[dataTabelName].DefaultView.Count == 0)
                {
                    return false;

                }
                else
                {
                    return true;

                }

            }
            catch(Exception e)
            {
                SQLErr=e.Message.ToString();
                return false;
            }
            
        }

推荐答案

A ref 变量是一个正常变量 - 只是你可以通过在方法中设置它来改变外部世界的值。只有两种方法: ref out 变量。

唯一另一种方法是将bool的返回值更改为自定义类,键/值对,元组或字符串,对于无错误,返回为null。



但请注意,在你的代码中,当你返回false时,你并不总是设置错误信息......



好​​多了方法是使它成为 void 方法并在遇到问题时抛出异常。
A ref variable is a "normal variable" - it's just that you can change the value in the outside world by setting it inside the method. There are only two ways to do that: ref and out variables.
The only other way to do it is to change the return value from bool to a custom class, a key/value pair, a tuple, or a string which you return as null for "no error".

But do notice that in your code when you return false, you don't always set an error message ...

A much better approach would be to make it a void method and throw an exception when you encounter a problem.


您显示的代码建议您编写的代码容易受到 SQL Injection [ ^ ] 。您没有提供将参数传递给查询的方法,这意味着您必须使用字符串连接将它们传递给SQL。除了您将面临试图获得正确格式的问题之外,您还会将数据库全部置于意外或故意破坏状态。



更改代码以正确传递参数。并且不要在你的方法中捕获异常;让它传播到调用方法,以便它可以被知道如何处理它的代码捕获。

The code you've shown suggests that you're writing code which is vulnerable to SQL Injection[^]. You have provided no means to pass parameters to the query, which means you would have to use string concatenation to pass them to SQL. Aside from the problem you will face trying to get the correct format, you leave your database wide open to accidental or deliberate destruction.

Change your code to pass parameters properly. And don't catch the exception in your method; let it propagate to the calling method, so that it can be caught by code that knows how to deal with it.
public static class DataManager
{
    private static void PrepareCommand(SqlCommand command, string query, object[] parameters)
    {
        if (parameters != null && parameters.Length != 0)
        {
            if (parameters.All(p => p is SqlParameter))
            {
                command.Parameters.AddRange(parameters);
            }
            else if (parameters.Any(p => p is SqlParameter))
            {
                throw new InvalidOperationException("Cannot mix SqlParameter and raw value parameters.");
            }
            else
            {
                string[] parameterNames = new string[parameters.Length];
                for (int index = 0; index < parameters.Length; index++)
                {
                    string name = "@p" + index;
                    parameterNames[index] = name;
                    command.Parameters.AddWithValue(name, parameters[index] ?? DBNull.Value);
                }
                
                query = string.Format(CultureInfo.InvariantCulture, query, parameterNames);
            }
        }
        
        command.CommandText = query;
    }
    
    public static bool SelectFromTable(SqlConnection connection, string query, DataSet ds, string dataTableName, params object[] parameters)
    {
        if (connection == null) throw new ArgumentNullException(nameof(connection));
        if (string.IsNullOrEmpty(query)) throw new ArgumentNullException(nameof(query));
        if (ds == null) throw new ArgumentNullException(nameof(ds));
        if (string.IsNullOrEmpty(dataTableName)) throw new ArgumentNullException(nameof(dataTableName));
        
        using (var command = new SqlCommand(null, connection))
        {
            PrepareCommand(command, query, parameters);
            
            var dataAdapter = new SqlDataAdapter(command);
            dataAdapter.Fill(ds, dataTableName);
        }
        
        return ds.Tables[dataTableName].DefaultView.Count != 0;
    }
}



然后您可以正确地将参数传递给查询:


You can then pass parameters to the query correctly:

private void btnOpenTable_Click(object sender, EventArgs e)
{
    try
    {
        var ds = new DataSet();
        string query = "SELECT Name, MainCode FROM banna.dbo.chartofaccounts WHERE MainCode Like {0} And db_confirm != {1} ORDER BY MainCode";
        if (DataManager.SelectFromTable(cnMain, query, ds, "T", txtMainCode.Text, txtConfirm.Text))
        {
            DataTable dt = ds.Tables[0];
            textBox1.Text = Convert.ToString(dt.Rows[0]["name"]);
            dataGridView1.DataSource = dt;
        }
    }
    catch (SqlException ex)
    {
        MessageBox.Show(ex.Message);
    }
}



或者,您可以传递 SqlParameter 对象:


Alternatively, you can pass SqlParameter objects:

string query = "SELECT Name, MainCode FROM banna.dbo.chartofaccounts WHERE MainCode Like @MainCode And db_confirm != @Confirm ORDER BY MainCode";

var parameters = new[] 
{ 
    new SqlParameter("@MainCode", txtMainCode.Text),
    new SqlParameter("@Confirm", txtConfirm.Text)
};

if (DataManager.SelectFromTable(cnMain, query, ds, "T", parameters))
...





< hr> 关于SQL注入的所有想法(但不敢问)|特洛伊亨特 [ ^ ]

如何在没有技术术语的情况下解释SQL注入? |信息安全堆栈交换 [ ^ ]

查询参数化备忘单| OWASP [ ^ ]




Everything you wanted to know about SQL injection (but were afraid to ask) | Troy Hunt[^]
How can I explain SQL injection without technical jargon? | Information Security Stack Exchange[^]
Query Parameterization Cheat Sheet | OWASP[^]


这篇关于如何使类中的方法返回消息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆