【发布时间】:2017-11-12 18:25:42
【问题描述】:
我正在尝试学习在 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
【问题讨论】:
-
我不知道你是不是这个意思,但你去吧:
-
是的,但一般来说,如果有人向您询问更多信息,最好将其添加到问题中,而不是在 cmets 中。另外,我错过了你代码的查询部分,不知道为什么我没有看到它,但我没有看到你的其余代码,所以我试图找到包含
b的错误来源。跨度> -
如何在 cmets 中发布代码? -_-
-
一般来说,您不应该 - 您应该将其添加到您的问题中。 cmets中的代码很难看懂。
-
@Touareg 删除的答案看起来是正确的,但不确定为什么会被删除。连接字符串时缺少空格,变为“... b.IngredientIdWHERE b.RecipeId ...”。您应该考虑使用逐字字符串文字(带有 @ 前缀),它使您能够创建多行字符串文字并避免此类问题。
标签: c# database winforms visual-studio-2017