Reputation: 1
I'm a beginner in c#.net. I'm having problem in binding the database (mysql) to datagridview. The error shows that my query is wrong. I pretty sure the query was right as I tested it on MySQL script. And I try to show it in datagridview by the way. dbMetName is datagridview. Here is my code
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);
}
}
Passing value from getData form
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;
}
}
}
}
Upvotes: 0
Views: 1334
Reputation: 374
ExecuteNonQuery returns nothing but the number of affected lines. Try this:
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;
}
Upvotes: 0
Reputation: 460288
There's a missing space between Metabolite_Name
and FROM
:
"SELECT Metabolite_Name" +
"FROM " + database +
Upvotes: 1