开发者

problem with mysql stored procedure when working in C# Visual Studio

开发者 https://www.devze.com 2023-04-05 06:29 出处:网络
I\'m new to MySQL and now i hava a project which must work with 开发者_Go百科MYSQL. It\'s a win application and I use C# on Visual Studio 2010. I tried to write a simple stored procedure like this:

I'm new to MySQL and now i hava a project which must work with 开发者_Go百科MYSQL. It's a win application and I use C# on Visual Studio 2010. I tried to write a simple stored procedure like this:

DELIMITER $$

CREATE DEFINER=`root`@`localhost` PROCEDURE `GetBank`()
BEGIN
SELECT * FROM BANKNAME;
END

And my C# code is here:

private void btnShow_Click(object sender, EventArgs e)
{
  MySqlConnection con = new MySqlConnection("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456");
  con.Open();
  DataTable dt = new DataTable();
  MySqlCommand cm = new MySqlCommand("GetBank", con);
  cm.CommandType = CommandType.StoredProcedure;
  MySqlDataAdapter da = new MySqlDataAdapter(cm);
  da.Fill(dt);
  con.Close();
  dataGridView1.DataSource = dt;
}

My test is to show the data in datagridview when clicking the button. It shows fine on the first click but when I click again, the data in datagridview is gone. The next click will show the data again and repeatedly.

But this code will be perfect when not working with stored procedured

private void btnShow_Click(object sender, EventArgs e)
{
  MySqlConnection con = new MySqlConnection("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456");
  con.Open();
  DataTable dt = new DataTable();
  MySqlCommand cm = new MySqlCommand("Select * from bankname", con);
  cm.CommandType = CommandType.Text;
  MySqlDataAdapter da = new MySqlDataAdapter(cm);
  da.Fill(dt);
  con.Close();
  dataGridView1.DataSource = dt;
}

So what's wrong with MySQL? Thanks in advance


The syntax to call your procedure in MySQL is

CALL GetBank()

so

MySqlCommand cm = new MySqlCommand("CALL GetBank()", con);

should do it. Which also removes the need to specify that your command cm is a stored procedure.


This problem is solved! Instead of using ordinary way to interact with MySQL: open a connection, create a command and use a data adapter to fill datatable, I use a MySQLHelper class and it works fine for me:

DataTable dt = MySqlHelper.ExecuteDataset("SERVER=localhost;DATABASE=dowacodb;UID=root;PASSWORD=123456", "call getbank()").Tables[0];
dataGridView1.DataSource = dt;

But now I wonder why this way works while the older way doesn't ?

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号