get data from variable table and return as datatable c#

╄→гoц情女王★ 提交于 2019-12-24 23:16:56

问题


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".

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.


回答1:


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);*/


来源:https://stackoverflow.com/questions/5986662/get-data-from-variable-table-and-return-as-datatable-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!