当 运行 一个 ExecuteNonQuery() 时,是什么导致错误“The ConnectionString 属性 has not been initialized”?

What causes the error "The ConnectionString property has not been initialized” when running an ExecuteNonQuery()?

每次我尝试连接到数据库时,它都会给我这个错误:

The ConnectionString property has not been initialized

我该怎么做才能解决这个问题?

这是我的代码:

private void OKButton_Click(object sender, EventArgs e)
{
    SqlConnection conn = new SqlConnection();
    conn.ConnectionString = "Data Source = ; Initial Catalog = ; USER ID = ; PASSWORD = ;";                     

    string sql = (@"INSERT INTO (1, 2, 3) VALUES('"+1b.Text+"', '"+2b.Text+"','"+3b.Text+"');");

    SqlCommand cmd = new SqlCommand(sql, conn);           
    cmd.Parameters.AddWithValue("@1", 1b.Text);
    cmd.Parameters.AddWithValue("@2", 2b.Text);
    cmd.Parameters.AddWithValue("@3", 3b.Text);        
    conn.Open();
    cmd.Connection = conn;
    cmd.ExecuteNonQuery();
    conn.Close();
}


private void CloseButton_Click(object sender, EventArgs e)
{
    Close(); //<---ExecuteNonQuery error in here
}

将 sql 命令更改为这种形式:

// see how to use parameters

string sql = @"INSERT INTO TableName (col1, col2, col3) VALUES(@p1, @p2, @p3);

SqlCommand cmd = new SqlCommand(sql, conn);

cmd.Parameters.AddWithValue("@p1", 1b.Text);

cmd.Parameters.AddWithValue("@p2", 2b.Text);

cmd.Parameters.AddWithValue("@p3", 3b.Text);