Fill DataTable from SQL Server database

前端 未结 2 669
我寻月下人不归
我寻月下人不归 2020-12-03 08:59

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 a

相关标签:
2条回答
  • 2020-12-03 09:22

    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;
        }
    }
    

    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

    0 讨论(0)
  • 2020-12-03 09:43

    Try with following:

    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);
            SqlDataAdapter da=new SqlDataAdapter(cmd);
            DataTable dt = new DataTable();
            da.Fill(dt);
            sqlConn.Close();
            return dt;
        }
    

    Hope it is helpful.

    0 讨论(0)
提交回复
热议问题