creating a database query METHOD

后端 未结 4 1676
旧巷少年郎
旧巷少年郎 2020-12-13 16:24

I\'m not sure if im delluded but what I would like to do is create a method that will return the results of a query, so that i can reuse the connection code. As i understand

4条回答
  •  佛祖请我去吃肉
    2020-12-13 17:18

    Hey! Try this, If you just want to display the names of all employees into a listBox, this should work. I just edited some lines from your code...

    Form1()
    {
        InitializeComponent();
        openFileDialog1.ShowDialog();
        openedFile = openFileDialog1.FileName;
    
        lbxEmployeeNames.DataSource = Query("Select [name] FROM [Employees$]");
        lbxEmployeeNames.DisplayMember = "name"; // The column you want to be displayed in your listBox.
    }
    
    // Return a DataTable instead of String.
    public DataTable Query(string sql)
    {
        System.Data.OleDb.OleDbConnection MyConnection;
        string connectionPath;
    
        //build connection string
        connectionPath = "provider=Microsoft.Jet.OLEDB.4.0;Data Source='" + openedFile + "';Extended Properties=Excel 8.0;";
    
        MyConnection = new System.Data.OleDb.OleDbConnection(connectionPath);
        MyConnection.Open();
        System.Data.OleDb.OleDbDataAdapter myDataAdapter = new System.Data.OleDb.OleDbDataAdapter(sql, MyConnection);
        DataTable dt = new DataTable();
        myDataAdapter.Fill(dt);
        return dt;
    }
    

提交回复
热议问题