从SQL Server数据库填充的DataTable [英] Fill DataTable from SQL Server database

查看:174
本文介绍了从SQL Server数据库填充的DataTable的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这一个对我来说是一个谜,我知道code我把它从别人,在我的情况下,它返回的数据表是空的。

This one is a mystery for me, I know the code I took it from others, in my case the datatable it returns is empty

构造是连接字符串,设置为全局字符串

conSTR is the connection string, set as a global string

public DataTable fillDataTable(string table)
    {
        string query = "SELECT * FROM dstut.dbo." +table;

        SqlConnection sqlConn = new SqlConnection(conSTR);
        sqlConn.Open();
        SqlCommand cmd = new SqlCommand(query, sqlConn);

        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        sqlConn.Close();
        return dt;
    }

修改1 结果
整点是以后显示此表中的一个TabControl一个DataGrid来看,这里是这个问题
<一href=\"http://stackoverflow.com/questions/16917046/displaying-multiple-datatable-in-tabcontrol-c-sharp\">displaying在TabControl的C#多个数据表

这只是显示的我一个空白的datagridview

Here it just show's me a blank datagridview

编辑2 结果
尝试所有这些,当我尝试显示表,在DataGridView是空的,有行权量,但现在值

EDIT 2
Tried them all, when I try to display the table, the datagridview is empty, have the right amount of rows but now value

推荐答案

如果变量包含无效字符(如空格),你应该周围添加变量方括号。

If the variable table contains invalid characters (like a space) you should add square brackets around the variable.

public DataTable fillDataTable(string table)
{
    string query = "SELECT * FROM dstut.dbo.[" + table + "]";

    using(SqlConnection sqlConn = new SqlConnection(conSTR))
    using(SqlCommand cmd = new SqlCommand(query, sqlConn))
    {
        sqlConn.Open();
        DataTable dt = new DataTable();
        dt.Load(cmd.ExecuteReader());
        return dt;
    }
}

顺便说一句,非常小心这种code,因为是开放的SQL注入攻击。我希望你的表名并非来自用户的输入

By the way, be very careful with this kind of code because is open to Sql Injection. I hope for you that the table name doesn't come from user input

这篇关于从SQL Server数据库填充的DataTable的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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