0

我需要为 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;
4

1 回答 1

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 注入。但这应该让你继续前进。

于 2013-07-02T13:21:15.867 回答