使用SQLConnection编译错误

时间:2016-11-13 15:38:11

标签: c# .net datatable sqlcommand sqldataadapter

我的语法显示了这些错误:

  

名称'命令'不存在   名字' conn'不存在

我正在声明这两个变量,为什么我会收到错误?这是完整的语法。

namespace SQLDataPull
{
public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private void button1_Click(object sender, EventArgs e)
    {
        SQL.DataTable dtData = new SQL.DataTable();
        string conString = @"Server=ProdDev;Database=Test;Integrated Security=SSPI;";
        StringBuilder query = new StringBuilder();
        SQL.DataTable dtProducts = new SQL.DataTable();
        query.Append("SELECT Top 1 [saleID] FROM [dbo].[saleorderitems] ORDER BY [saleID] ASC");
        //Populating datatable1 with the saleID
        using (SqlConnection cn = new SqlConnection(conString))
        {
            using (SqlDataAdapter da = new SqlDataAdapter(query.ToString(), cn))
                da.Fill(dtProducts);
        }
        //Iterating the saleid from datatable
        foreach (DataRow row in dtProducts.Rows)
        {
            using (SqlConnection conn = new SqlConnection("Server=ProdDev;Database=Test;Integrated Security=SSPI;")
            {
                SqlCommand command = new SqlCommand();
                command.CommandText = "SELECT * FROM [dbo].[master] WHERE saleID = @saleID;";
                command.Parameters.Add("@saleID", SqlDbType.VarChar);
                command.Parameters["@saleID"].Value = row.Field<string>("saleID");
                command.Connection = conn;                    
                using (SqlDataAdapter dataadapter1 = new SqlDataAdapter()
                {
                    dataadapter1.Fill(dtData);
                }
            }
        }  
    }
}
}

2 个答案:

答案 0 :(得分:1)

您忘记在2个地方关闭括号)

using (SqlConnection conn = 
       new SqlConnection("Server=ProdDev;Database=Test;Integrated Security=SSPI;"))

using (SqlDataAdapter dataadapter1 = new SqlDataAdapter())

答案 1 :(得分:0)

您在使用声明的末尾忘记了一个)

using (SqlConnection conn = new 
             SqlConnection("Server=ProdDev;Database=Test;Integrated Security=SSPI;")

使用

using (SqlConnection conn = new 
              SqlConnection("Server=ProdDev;Database=Test;Integrated Security=SSPI;"))

你还需要做同样的事情:

using (SqlDataAdapter dataadapter1 = new SqlDataAdapter())