与SQL Server数据库相关的语法错误

时间:2017-11-12 18:25:42

标签: c# database winforms visual-studio-2017

我正在尝试学习在visual studio上使用数据库。我已经从YouTube上的一个人那里复制了以下代码而没有任何错误,但我仍然收到错误。

我遇到以下代码的问题:

public partial class FormMain : Form
{
    SqlConnection connection;

    string ConnectionString;

    public FormMain()
    {
        InitializeComponent();

        ConnectionString = ConfigurationManager.ConnectionStrings["denis_project.Properties.Settings.denisdatabaseConnectionString"].ConnectionString;
    }

    private void FormMain_Load(object sender, EventArgs e)
    {
        PopulateRecipes();
    }

    private void PopulateRecipes()
    {
        using (connection = new SqlConnection(ConnectionString))
        using(SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROM Recipe", connection))
        {             
            DataTable recipeTable = new DataTable();
            adapter.Fill(recipeTable);

            lstRecipes.DisplayMember = "Name";
            lstRecipes.ValueMember = "Id";
            lstRecipes.DataSource = recipeTable;
        }
    }

    private void PopulateIngredients()
    {
        string query = "SELECT a.Name FROM Ingredient a " +
            "INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId" +
            "WHERE b.RecipeId = @RecipeId";

        using (connection = new SqlConnection(ConnectionString))
        using (SqlCommand command = new SqlCommand(query, connection))
        using (SqlDataAdapter adapter = new SqlDataAdapter(command))
        {
            command.Parameters.AddWithValue("@RecipeId", lstRecipes.SelectedValue);

            DataTable ingredientTable = new DataTable();
            adapter.Fill(ingredientTable);

            lstIngredients.DisplayMember = "Name";
            lstIngredients.ValueMember = "Id";
            lstIngredients.DataSource = ingredientTable;
        }
    }

    private void lstRecipes_SelectedIndexChanged(object sender, EventArgs e)
    {
        PopulateIngredients();
    }
}

问题是此代码在此行引发错误:

 adapter.Fill(ingredientTable);

错误说:

  

System.Data.SqlClient.SqlException:''b'附近的语法不正确。'

我试图查找代码中的任何错误,但我没有发现任何错误。

也许这有帮助,我从SQLQuery1.sql复制了它:

 SELECT * FROM recipe

 SELECT * FROM Ingredient

 SELECT a.Name 
 FROM Ingredient a
 INNER JOIN RecipeIngredient b ON a.Id = b.Ingredientid

1 个答案:

答案 0 :(得分:1)

可能是你应该在WHERE子句之前添加一个空格:

string query = "SELECT a.Name FROM Ingredient a " +
            "INNER JOIN RecipeIngredient b ON a.Id = b.IngredientId" +
            " WHERE b.RecipeId = @RecipeId";