从变量表中获取数据并返回的数据表中的C# [英] get data from variable table and return as datatable c#

查看:556
本文介绍了从变量表中获取数据并返回的数据表中的C#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从指定的表retrive所有的数据,我不需要对数据进行强类型,所以我返回它作为一个数据表。

I need to get retrive all of the data from specified tables and I don't need the data to be strongly typed so I am returning it as a data table.

public DataTable GetByTypeName(String t)
    {
        var type = Type.GetType(t);

        var dt = new DataTable();

        using (var sqlConn = new SqlConnection(ConfigurationManager.ConnectionStrings["MasterPlanConnectionString"].ConnectionString))
        {
            var sqlComm = new SqlCommand("SELECT * FROM @table", sqlConn);
            sqlComm.Parameters.AddWithValue("@table", type.Name);

            sqlConn.Open();

            var dr = sqlComm.ExecuteReader(CommandBehavior.CloseConnection);

            dt.Load(dr);
        }

        return dt;
    }

当我运行此我得到的错误

When I run this I get the error

System.Data.SqlClient.SqlException was unhandled by user code
Message=Must declare the table variable "@table".

我不明白为什么这是行不通的,因为我已经声明@table。我知道这个方法是开放的一些不好的SQL攻击,所以打算在究竟是什么类型的,可以查询对一些保障补充。

I cannot figure out why this isn't working as I have declared @table. I know this method is open to some bad sql attacks so I plan to add in some protection about exactly what types can be queried against.

推荐答案

您可以动态地构造查询 - (应该没在这里,但可能会暴露你的查询SQL注入)

You can construct your query dynamically - (should be ok over here, but may expose your query to sql injection)

        var query = String.Fromat("Select * from [{0}]", type.Name);
        var sqlComm = new SqlCommand(query, sqlConn);
        /*sqlComm.Parameters.AddWithValue("@table", type.Name);*/

这篇关于从变量表中获取数据并返回的数据表中的C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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