0

我是 c#.net 的初学者。我在将数据库(mysql)绑定到 datagridview 时遇到问题。该错误表明我的查询是错误的。我很确定查询是正确的,因为我在 MySQL 脚本上对其进行了测试。顺便说一下,我尝试在 datagridview 中显示它。dbMetName 是数据网格视图。这是我的代码

private void Binding()
    {
        string connStr = "datasource=localhost;port=3306;username=root;password=root;";
        conn = new MySqlConnection(connStr);
        MySqlCommand command = conn.CreateCommand();
        try
        {
            string database = schemaForm.getData;
            dtable = new DataTable();
            bindingSource = new BindingSource(); ;

                conn.Open();
                command.CommandText = "SELECT Metabolite_Name" +
                                      "FROM " + database +
                                      ".Metabolites WHERE"+
                                      " MetaboliteID IN ('met1', 'met2');";
                command.ExecuteNonQuery();
                sqlData.SelectCommand = command;
                sqlData.Fill(dtable);
                bindingSource.DataSource = dtable;
                dbMetName.DataSource = dtable;
                dtable.Columns.Add("Metabolite Name");
                dbMetName.DataSource = dtable;
                conn.Close();        
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

从 getData 表单传递值

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace DynamicSimulator_v2
{
       public partial class SchemaName : Form
   {
      private static string data;
    public SchemaName()
    {
        InitializeComponent();
    }

    private void btnCancel_Click(object sender, EventArgs e)
    {
        this.Hide();
    }

    private void btnOK_Click(object sender, EventArgs e)
    {
        data=txtDB.Text;
        this.Hide();
    }

    public string getData
    {
        set
        {
            data = txtDB.Text;
        }
        get
        {
          return data;
          }
        }
      }
    }
4

2 回答 2

1

Metabolite_Name和之间缺少空格FROM

"SELECT Metabolite_Name" +
"FROM " + database +
于 2013-10-20T19:59:45.800 回答
0

ExecuteNonQuery 只返回受影响的行数。尝试这个:

public DataTable GetDBDataTable(MySqlConnection dbconnection, string table, string columns = "*", string clause = "")
{
    MySqlCommand mysqlcmd = new MySqlCommand("SELECT " + columns + " FROM " + table + " " + clause +";", dbconnection);
    MySqlDataAdapter mysqlad = new MySqlDataAdapter(mysqlcmd);
    DataSet ds = new DataSet();
    mysqlad.Fill(ds);
    DataTable dt = ds.Tables[0];
    return dt;
}
于 2013-10-25T09:10:58.587 回答