我正在尝试用 C# 创建一个 Windows 窗体应用程序,主要是为了练习我在大学学到的知识。我的数据库是由三个表(SetIndex、SetSong [联结表] 和 Song)组成的 Access 数据库。我们从未学习过如何在应用程序中使用数据库,只是在网站中。我学到的大部分知识都是通过反复试验学到的。
我有一个组合框列表,其中包含 SetIndex 表中的日期,值是 ID(SetIndex 的主键)。我需要能够使用 setindex.id = setsong.setid and setsong.songid = song.id and setIndex.id = a variable, the chosen value from the dropdown list 的选择语句来查询数据库。我在 Access 中使用 (setindex.id = ?) 编写了一个 select 语句,它在 Access 中运行良好,但我还没有弄清楚如何在 C# 中执行此操作。我找到了有关如何使用参数和如何查询多个表的答案,但没有找到将两者结合起来的答案。
那么有没有办法在代码中做到这一点?
这是我尝试的最后一件事:
using (OleDbConnection dataConnection = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Mandy\Documents\Visual Studio 2010\Projects\SetManager1.3\SetManager1.3\SetManager.accdb"))
{
using (OleDbCommand dataCommand = dataConnection.CreateCommand())
{
dataCommand.CommandText = "SELECT Title FROM Song WHERE Song.ID = SetSong.SongID AND SetIndex.ID=SetSong.SetID AND SetIndex.ID=@ID";
dataConnection.Open();
dataCommand.Parameters.AddWithValue("@ID", ID);
DataTable table = new DataTable();
OleDbDataAdapter adapter = new OleDbDataAdapter();
adapter.SelectCommand = dataCommand;
adapter.Fill(table);
bindingSource1.DataSource = table;
dataGridView1.AutoResizeColums(DataGridViewAutoSizeColumnsMode.AllCellsExceptHeader);
dataGridView1.ReadOnly = true;
dataGridView1.DataSource = bindingSource1;
}
}
ID 是一个来自全局类的 int 变量,该类从列出日期的组合框中获取 ID 值(所选 SetIndex.ID 的值)。我通过使用标签和按钮进行测试以确保这部分工作正常,它似乎正在检索值,将其存储在 GlobalClass.ViewBySetDate 中,然后将其转换为我的 int ID 就好了。
但这会出现错误“没有为一个或多个必需参数给出值。”
是否有更好/有效的方法来做到这一点?或者,如果没有,我该如何修复错误?
提前谢谢你,
曼迪
编辑:我将 Select 语句更改为以下内容:
SELECT song.Title FROM SetIndex INNER JOIN (song INNER JOIN SetSong ON song.ID = SetSong.SongID) ON SetIndex.ID = SetSong.SetID WHERE ((set index.id) =[?]);
错误没有了,但是datagridview还是一片空白。
最佳答案
测试你在数据库中查询.. Access 数据库的方法是一样的,但是你的查询是错误的
SELECT Title FROM Song WHERE Song.ID = SetSong.SongID AND SetIndex.ID=SetSong.SetID AND SetIndex.ID=@ID
SetSong 未在查询中定义。
关于c# - 如何从带有变量的 Access 数据库运行 C# 中的 Select 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10097207/