iT邦幫忙

1

c#存取mySQL資料庫 ,出現錯誤訊息(vs2017)?

作業系統:win10
vs 2017

我用 c#存取mySQL資料庫 ,出現底下錯誤訊息

csAPP系統訊息D1: Procedure or function 'delete from member where mem_no=1' cannot be found in database 'test01'. Verify that user 'sa'@'192.168.1.21' has enough privileges to execute.
csAPP系統訊息D2: Procedure or function 'delete from member ' cannot be found in database 'test01'. Verify that user 'sa'@'192.168.1.21' has enough privileges to execute.

mysql帳號sa.權限是全部開啟的...

我使用同一個連線,對資料庫做存取..
一開始的時候,啟動連線,程式結束才關閉連線

command,reader也是使用同一個
MySqlCommand command;
MySqlDataReader reader ;

程式 第347/348/349行
我把註解拿掉,就沒錯誤訊息
//conn.Close();
// conn.Open();
// command = conn.CreateCommand();

想不出是哪裡出了??

底下全部的程式碼

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

using System.Data;
using MySql.Data;
using MySql.Data.MySqlClient;

namespace ConsoleApp1
{
    class Program
    {
        /// <summary>
        /// 
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {

            string dbHost = "192.168.1.21";//資料庫位址
            string dbUser = "sa";//資料庫使用者帳號
            string dbPass = "661ho728";//資料庫使用者密碼
            string dbName = "test";//資料庫名稱

            MySqlConnection conn;
            MySqlCommand command;
            MySqlDataReader reader ;

            MySqlCommand command2;
            MySqlDataReader reader2;
            string connStr;

            string CommStr = "";
            int n = 0;

            //開始連線
            connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
            conn = new MySqlConnection(connStr);
            command = conn.CreateCommand();
            command2 = conn.CreateCommand();
            conn.Open();

            //刪除資料庫
            try
            {
                CommStr = "drop database IF EXISTS test01 ;";
                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("刪除1筆資料庫test01", n);

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }

            //建立資料庫
            try
            {
                CommStr = "create database test01 DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;";
                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("建立1筆資料庫test01", n);

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }

            //刪除使用者帳號
            try
            {
                CommStr = "DROP USER IF EXISTS 'user'@'%';";
                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("刪除1筆使用者帳號user", n);

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }

            //建立使用者帳號&密碼
            try
            {
                CommStr = "CREATE USER 'user'@'%' IDENTIFIED BY 'password';";
                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("建立1筆使用者帳號user", n);

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }

            //建立使用者權限
            try
            {
                CommStr = "GRANT ALL PRIVILEGES ON test01.* TO 'user'@'%';";
                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("使用者權限設定");

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }

            //關閉連線
            conn.Close();


            //
            //
            //開始連線
            dbName = "test01";
            connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
            conn = new MySqlConnection(connStr);
            command = conn.CreateCommand();
            conn.Open();



            //建立資料表
            try
            {
                    //string 前面 加上@ ,可以多行串接
                CommStr = @"CREATE TABLE member (  
                              mem_no INT NOT NULL AUTO_INCREMENT, 
                              mem_name varchar(50) NOT NULL,  
                              mem_addr varchar(50) not null,  
                              PRIMARY KEY(mem_no)     
                            ); ";

                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("建立1筆資料表member", n);

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }


            //建立存儲過程stored procedure
            try
            {
                //string 前面 加上@ ,可以多行串接
                CommStr = @"
                       
                        DROP PROCEDURE IF EXISTS sp01;
                        CREATE PROCEDURE sp01 (m_name varchar(50))
                        BEGIN
		                        SELECT mem_no,mem_name,mem_addr
		                        FROM member
		                        WHERE mem_name = m_name;
                        END;

                             ";

                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("建立1筆stored procedure", n);

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }



            //新增會員資料
            try
            {

                for (int i = 1; i < 11; i++)
                {
                    //string 前面 加上@ ,可以多行串接
                    string str01 = "user" + Convert.ToString(i);
                    CommStr = @"INSERT INTO member (mem_no, mem_name,mem_addr)
                                 VALUES ( "+i+", '"+str01+"' ,'home') ;";

                    command.CommandText = CommStr;
                    n = command.ExecuteNonQuery();

                    Console.WriteLine("建立{0}筆資料member", n);
                }


                

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }

            //修改資料member 2
            try
            {

                    //string 前面 加上@ ,可以多行串接
                    //string str01 = "user" + Convert.ToString(i);
                    CommStr = @"UPDATE member set mem_name='AAA'
                                 where mem_no='2' ;";

                    command.CommandText = CommStr;
                    n = command.ExecuteNonQuery();

                    Console.WriteLine("建立{0}筆資料member", n);
 

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }


            //修改資料member 3
            try
            {

                //string 前面 加上@ ,可以多行串接
                //string str01 = "user" + Convert.ToString(i);
                CommStr = @"UPDATE member set mem_name='AAA'
                                 where mem_no='3' ;";

                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("建立{0}筆資料member", n);


            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }

            //修改資料member 
            try
            {

                //string 前面 加上@ ,可以多行串接
                //string str01 = "user" + Convert.ToString(i);
                CommStr = @"UPDATE member set mem_name='BBB'
                                 where mem_name='AAA' ;";

                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("建立{0}筆資料member", n);


            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息: " + ex.Message.ToString());
            }

            Console.Write("\n");
            Console.Write("列單 資料member\n");
            //列單 資料member 
            try
            {

                //string 前面 加上@ ,可以多行串接
                //string str01 = "user" + Convert.ToString(i);
                CommStr = @"select * from member ;";

                command.CommandText = CommStr;
                reader = command.ExecuteReader(); //execure the reader

                while (reader.Read())
                {
 
                        String mem_no = reader.GetString(0);
                        String mem_name = reader.GetString("mem_name");
                        String mem_addr = reader["mem_addr"].ToString();


                        Console.Write(mem_no + "\t" +mem_name +"\t"+ mem_addr);
 
                    Console.Write("\n");
                }
                reader.Close(); //關閉..才能對資料表做動作(刪除)
                reader.Dispose();
                //command.Clone(); 
                //command.Dispose(); 
            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息A: " + ex.Message.ToString());
            }

            

            Console.Write("\n");
            Console.Write("列單 資料member  stored procedure\n");
            //列單 資料member  stored procedure
            try
            {
                command.Parameters.Clear();
                command.CommandType = CommandType.StoredProcedure;
                command.CommandText = "sp01";
                command.Parameters.Add("?m_name", MySqlDbType.VarChar).Value = "BBB";

                reader = command.ExecuteReader(CommandBehavior.SingleResult);
                //reader = command.ExecuteReader(CommandBehavior.SingleRow);

                while (reader.Read())
                {

                    String mem_no = reader.GetString(0);
                    String mem_name = reader.GetString("mem_name");
                    String mem_addr = reader["mem_addr"].ToString();


                    Console.Write(mem_no + "\t" + mem_name + "\t" + mem_addr);

                    Console.Write("\n");
                }
                reader.Close(); //關閉..才能對資料表做動作(刪除)
                reader.Dispose();
            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息B: " + ex.Message.ToString());
            }

            //底下三行註解拿掉,錯誤訊息就沒有了
           //conn.Close(); 
           // conn.Open();
           // command = conn.CreateCommand();


            //指定刪除某一筆資料 
            try
            {
                //string 前面 加上@ ,可以多行串接
                CommStr = "delete from member where mem_no=1 ";

                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("刪除{0}筆資料member", n);

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息D1: " + ex.Message.ToString());
            }


            //刪除全部資料 
            try
            {
                //string 前面 加上@ ,可以多行串接
                CommStr = "delete from member ; ";

                command.CommandText = CommStr;
                n = command.ExecuteNonQuery();

                Console.WriteLine("刪除{0}筆資料member", n);

            }
            catch (Exception ex)
            {
                Console.WriteLine("csAPP系統訊息D2: " + ex.Message.ToString());
            }




            //關閉連線
            conn.Close();
            conn.Dispose();




        }
    }
}

這個SQL實際工作執行~
是分成各網頁功能處理的~
沒有照範例一頁測試到底@@..
畢竟新手會霧煞煞....
我先連到test資料庫..創建test01資料庫
然後才連到test01
我主要想練習 資料庫的建立/使用者建立/資料表的建立/資料的存取

想先用控制台 模式 執行
我找出解決的方法了

每一個使用command的地方

前面 加一個

command = conn.CreateCommand(); //這行要加入

就能避免問題

2 個回答

2
咖咖拉
iT邦研究生 2 級 ‧ 2021-03-23 09:33:19

是這邊的問題嗎?

            //開始連線
            dbName = "test01";
            connStr = "server=" + dbHost + ";uid=" + dbUser + ";pwd=" + dbPass + ";database=" + dbName;
            conn = new MySqlConnection(connStr);
            command = conn.CreateCommand();
            conn.Open();

dbName = "test01";

小魚 iT邦大師 1 級 ‧ 2021-03-23 13:29:40 檢舉

說到連線字串,
每種DB都不大一樣,
我後來都直接用微軟提供的SqlConnectionStringBuilder來處理了.

我先連到test資料庫..創建test01資料庫
然後才連到test01
我主要想練習 資料庫的建立/使用者建立/資料表的建立/資料的存取

2
海綿寶寶
iT邦大神 1 級 ‧ 2021-03-23 10:01:27

因為你 339 列有寫關閉..才能對資料表做動作(刪除)

所以,在 346 列加以下這段試試看

finally {
            if (reader != null) {
                reader.Close();
                reader.Dispose();
            }
        }

再不行連 if 都不要了,如下

finally {
            reader.Close();
            reader.Dispose();
        }

請教一下..我照你方法做..
他出現錯誤訊息

reader我不是已經宣告了..

https://ithelp.ithome.com.tw/upload/images/20210323/20013294rdzfdi8sFZ.png

xSummer iT邦新手 3 級 ‧ 2021-03-23 17:30:04 檢舉

沒事 我看錯了

我知道錯誤訊息怎麼排除了???

finally {
            if (reader != null) {
                reader.Close();
                reader.Dispose();
            }
        }

reader出現錯誤,把它移到try 就可以了

我要發表回答

立即登入回答