获取连接属性尚未设置错误

时间:2017-06-29 13:50:37

标签: c# mysql sql

如标题中所述,我试图在Visual Studio 2017上写一些准备好的声明。 但是在启动我的程序时,我有一个例外,叫做

  

System.InvalidOperationException:'连接属性没有   已经设定了。'

以下是相关代码:

namespace Sequence
{
   class Database
   {
    private MySqlCommand cmd;
    MySql.Data.MySqlClient.MySqlConnection conn;    //new connection

    public void Connect()
    {
        string myConnectionString;  //connection String

        myConnectionString = "server=127.0.0.1;uid=root;" +
    "pwd=;database=internship;";

        try
        {
            conn = new MySql.Data.MySqlClient.MySqlConnection(myConnectionString);
            conn.Open();
        }
        catch (MySql.Data.MySqlClient.MySqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }


    public void Disconnect()
    {
        try
        {
            conn.Close();
        }
        catch (MySql.Data.MySqlClient.MySqlException ex)
        {
            MessageBox.Show(ex.Message);
        }
    }

    public void AddData()
    {
        cmd = new MySql.Data.MySqlClient.MySqlCommand();
        //Connecting to database
        Connect();
        try
        {
            //Prepare a statement
            cmd.CommandText = "INSERT INTO storing VALUES(@longitude, @latitude, @status, @path)";
            cmd.Prepare();
            //Adding values
            cmd.Parameters.AddWithValue("@longitude", 0.5);
            cmd.Parameters.AddWithValue("@latitude", 0.5);
            cmd.Parameters.AddWithValue("@status", "false");
            cmd.Parameters.AddWithValue("@path", "C:\\temp\\sequence");
            //Executes the Query
            cmd.ExecuteNonQuery();
            //Writes in Console
            Console.WriteLine("Line added successfully");
        }
        catch (MySql.Data.MySqlClient.MySqlException ex)
        {
            MessageBox.Show("Error " + ex.Number + " has occured: " + ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }



        }

    }
}

这是我连接数据库的类。 我有一个主程序,我刚刚写了这个:

static class Program
{
    [STAThread]
    static void Main()
    {
        Database db = new Database();
        db.Connect();
        db.AddData();
        db.Disconnect();
    }
}

我知道为什么会遇到此异常?

我按照此链接上的教程: https://dev.mysql.com/doc/connector-net/en/connector-net-programming-prepared-preparing.html

提前致谢

1 个答案:

答案 0 :(得分:2)

您没有设置命令的连接属性:

cmd.Connection = conn;

虽然建议使用using-statement 提供方便的语法,以确保正确使用IDisposable对象,如SqlConnection。它还将关闭连接