如何从数据库Mysql中选择数据并将其添加到DataGridView上?

时间:2013-03-14 04:20:10

标签: c# mysql database select

这样做的目的是,如果您已加载数据并且想要使用textbox搜索此人的姓名,号码等并输入他的姓名,则会通过单击将其直接添加到空数据gridview按钮。

 string box = txtSearch.Text;
            string table = "reservations";
            string query = "SELECT FROM reservations WHERE Client like '%" + box;
            connection.Open();
            MySqlDataAdapter da_res = null;
            DataSet ds_res = null;
            ds_res = new DataSet();
            da_res = new MySqlDataAdapter(query, connection);
            da_res.Fill(ds_res, table);

            dgvUser.DataSource = ds_res.Tables[table];

这是代码实际上我有6个colums我到目前为止只尝试了一个。 erorr发生在da_res.Fill(ds_res, table);

这是erorr的详细信息:

您的SQL语法有错误;查看与您的MySQL服务器版本对应的手册,以便在第1行“FROM预订WHERE客户端”'%name client'附近使用正确的语法“

MySqlConnection connection = null;
            string hostname = "localhost";
            string database = "aparece_hoteldb";
            string username = "root";
            string password = "";
            connection = new MySqlConnection("host=" + hostname +
                                            ";database=" + database +
                                            ";username=" + username +
                                            ";password=" + password + ";");

1 个答案:

答案 0 :(得分:2)

Chage this:

string query = "SELECT FROM reservations WHERE Client like '%" + box;

到此:

string query = "SELECT * FROM reservations WHERE Client like '%" + box +"%'";

您没有选择任何列。

正如您在这里问的那样是一个适合您的工作示例(您确实需要学习使用谷歌)......

private void MainClass_Load(object sender, System.EventArgs e)
{
    string connectionString = @"Driver={MySQL};SERVER=localhost;DATABASE=NorthwindMySQL;";

    OdbcConnection conn= new OdbcConnection(connectionString);
    conn.Open();

    OdbcDataAdapter da = new OdbcDataAdapter ("SELECT CustomerID, ContactName, ContactTitle FROM Customers", conn);            

    DataSet ds = new DataSet("Cust");     
    da.Fill(ds, "Customers");

    dataGrid1.DataSource = ds.DefaultViewManager;
    conn.Close();
}