簡體   English   中英

連接必須有效且打開錯誤

[英]Connection must be valid and open error

我收到錯誤:啟動此程序時連接必須有效且打開。 我在谷歌上搜索,只發現 2 個人有相同的錯誤。 有可能解決這個問題嗎? 謝謝

using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using System.Data.Odbc;
using System.Data.Sql;
namespace WindowsFormsApplication1
{
static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        string connectionString = "Server=localhost;Uid=root;Pwd=******;Database=testing;";
        MySql.Data.MySqlClient.MySqlConnection connection = new MySql.Data.MySqlClient.MySqlConnection(connectionString);

        connection.Open();

        string insertQuery = "ALTER TABLE `user` ADD lol INT";
        MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery);
        myCommand.ExecuteNonQuery();
        connection.Close();
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new Form1());
    }
}
}

您需要告訴您的命令有關您的連接對象。 將連接參數添加到此行:

MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery, connection);

您的命令沒有連接assignet。 嘗試將連接傳遞給命令的構造函數,如下所示:

MySql.Data.MySqlClient.MySqlCommand myCommand = new MySql.Data.MySqlClient.MySqlCommand(insertQuery, connection);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM