Access数据库查询字符串

时间:2013-07-15 17:20:47

标签: c# asp.net sql database

我有一个包含两个表的数据库; StudentID是'StudentList'表的主键,StudentID是'JournalEntries'表中的外键。

在我的网站上,我有一个搜索功能,因此用户可以从StudentList中搜索学生,结果显示在数据网格中。当用户从列表中选择学生时,弹出日记输入框。当他们填写日记帐分录弹出框并单击提交按钮时,我需要将日记帐分录输入到与从数据网格中选择的学生ID相关联的JournalEntries表中。

protected void SearchGrid_SelectedIndexChanged(object sender, EventArgs e)
{
    FNameLabel.Text = SearchGrid.SelectedRow.Cells[1].Text;
    LNameLabel.Text = SearchGrid.SelectedRow.Cells[2].Text;

    string constr = @"Provider=Microsoft.Jet.OLEDB.4.0; Data Source=D:\Sites\Network2\nrsh\App_Data\myDB.mdb";
    string cmdstr = "SELECT StudentID FROM StudentList WHERE = SearchGrid.SelectedRow.Cells[3].Text AND INSERT into JournalEntries (Topic, SubTopic, Summary, Date, Notes) values (@Topic, @SubTopic, @Summary, @Date, @Notes)";

    OleDbConnection con = new OleDbConnection(constr);
    OleDbCommand com = new OleDbCommand(cmdstr, con);
    con.Open();
    //The following fields are added from the journal entry form to the corresponding database fields
    com.Parameters.AddWithValue("@Topic", ddlTopic.Text);
    com.Parameters.AddWithValue("@SubTopic", txtSubTopic.Text);
    com.Parameters.AddWithValue("@Date", txtDate.Text);
    com.Parameters.AddWithValue("@Summary", txtSummary.Text);
    com.Parameters.AddWithValue("@Notes", txtNotes.Text);
    com.ExecuteNonQuery();
    con.Close();
}

所以这是我对逻辑的想法,但它可能是完全错误的,因为我对sql知之甚少。任何帮助都会很棒。

2 个答案:

答案 0 :(得分:1)

您无法组合SELECT和INSERT语句。

.......

string myValue = SearchGrid.SelectedRow.Cells [3] .Text;

你的字符串中没有SearchGrid.SelectedRow.Cells [3] .Text的值。你实际上有“SearchGrid.SelectedRow.Cells [3] .Text”......

string myValue = SearchGrid.SelectedRow.Cells[3].Text;
string cmdstr = "INSERT into JournalEntries (StudentID , Topic, SubTopic, Summary, Date, Notes) values (@StudentID , @Topic, @SubTopic, @Summary, @Date, @Notes)";

以及后来的

com.Parameters.AddWithValue("@StudentID", myValue);
com.Parameters.AddWithValue("@Topic", ddlTopic.Text);
com.Parameters.AddWithValue("@SubTopic", txtSubTopic.Text);
com.Parameters.AddWithValue("@Date", txtDate.Text);
com.Parameters.AddWithValue("@Summary", txtSummary.Text);
com.Parameters.AddWithValue("@Notes", txtNotes.Text);

我有点猜。您应该提供表名和表中的所有列及其数据类型(int,string等)。

编辑:REFACTOR。

您应该创建一个接受参数的类。你永远不应该有数据库代码....坐在GUI代码所在的位置。

public class JournalEntriesManager
{

public static void InsertJournalEntry ( string studentID, string topic , string subTopic, DateTime DateOf  , string summary , string notes )
{
// Your code here
}

}

这就像“关注点分离”的“第1级”。

但简而言之,您的GUI级代码应收集来自控件的信息......并将该信息传递给BusinessLogic(在本例中为“JournalEntriesManager”)。 这样的事情。

答案 1 :(得分:0)

您不能将多个语句与AND语句完全组合,即将多个条件组合在一起。此外,您不能奇怪地将一个表中的行与另一个表中的行相关联,而是,您的JournalEntries表中应该包含另一列,其中包含与该条目关联的学生的ID。当您在JournalEntries表中插入新行时,您将在该列中包含学生ID,这就是您的日记条目与学生相关联的方式。

此外,您的查询不能包含变量名称,如“SearchGrid.SelectedRow.Cells [3] .Text”,您必须将该变量的值直接插入查询文本中。请记住,您将此查询发送到另一台服务器(您的数据库服务器),并且不知道您的脚本中的变量是什么。