从 SQL Server 数据库填充 DataTable [英] Fill DataTable from SQL Server database
问题描述
这个对我来说是个谜,我知道我从别人那里拿来的代码,在我的例子中它返回的数据表是空的
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
为连接字符串,设置为全局字符串
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 C#中显示多个数据表
这里只显示一个空白的数据网格视图
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
推荐答案
如果变量 table
包含无效字符(如空格),您应该在变量周围添加方括号.
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;
}
}
顺便说一句,这种代码要非常小心,因为它对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屋!