如何通过查询传递数据集

时间:2013-07-02 10:03:31

标签: c#

我需要获取p_cat组合框的数据库值.....但我无法在查询中传递数据集..

class Datatbl_Class1
{
    DataSet ds = new DataSet();

    public DataSet filldata(string q)
    {
        string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
        MySqlConnection con = new MySqlConnection(myconnection);
        MySqlCommand cmd = new MySqlCommand(q, con);
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);

        da.Fill(ds);
        return ds;
    }
}

Select_int_Class1 s4 = new Select_int_Class1();
string q = "SELECT Sup_ID FROM gtec_computer.supplier WHERE Sup_Name='" +p_cmb_sup.Text+ "'";

string ww = "Sup_ID";
int t = s4.select_val_int(q, ww);

DataSet n = new DataSet();
Datatbl_Class1 dt = new Datatbl_Class1();

string Query = "SELECT  Cat_ID FROM gtec_computer.supplier_detail WHERE Sup_Id="+t+" ";
n = dt.filldata(Query)

DataSet ds = new DataSet();
string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";

MySqlConnection con = new MySqlConnection(myconnection);
string q1 = "SELECT  cat_Name FROM gtec_computer.category WHERE Cat_ID= " + n + " ";
MySqlCommand cmd = new MySqlCommand(q1, con);
MySqlDataAdapter da1 = new MySqlDataAdapter(cmd);
da1.Fill(ds);
p_cat.DataSource = ds;

1 个答案:

答案 0 :(得分:0)

你应该可以通过参数来调用类中的函数调用...但是,通过构建命令字符串,你可以大开SQL注入。查看参数化查询。现在,回到原始代码和替代实现......

class Datatbl_Class1
{
    public DataSet filldata(string q )
    {
        string myconnection = "datasource=localhost;port=3306;username = root; password = 12345V";
        MySqlConnection con = new MySqlConnection(myconnection);
        MySqlCommand cmd = new MySqlCommand(q, con);
        MySqlDataAdapter da = new MySqlDataAdapter(cmd);

        DataSet ReturnThisOne = new DataSet();
        da.Fill(ReturnThisOne);
        return ReturnThisOne;
    }
}

不要将“ds”作为该类的属性。只需在方法中创建数据集的新实例即可。无论如何它将是一个指针。填写并将指针返回到调用源,因为您已经在使用“n = dt.filldata(Query)”。是的,该函数不再使用数据表,但由于它的引用正在返回,因此调用它的“n”位置将保留它。在“n”所在的函数被释放之前,它不会被释放到垃圾收集。

再次,查看参数以防止sql注入。但这应该让你前进。