1

我创建了一个将管理连接和命令的类,我将其命名为DbConfiguration,它使用单例模式(dbc用作对象名称)。

我的问题是,当我尝试运行时,此 SQL 语法会引发错误ExecuteNonQuery()

使用此连接字符串:

"Provider=Microsoft.ACE.OLEDB.12.0;dbms.accdb;Persist Security Info=False"

我首先执行了这个:

dbc.SetCommand("INSERT INTO inventory ([CallNumber], [Title], [ImageLocation]) VALUES (@CALLNUMBER, @TITLE, @IMAGELOC);");
dbc.GetCommand().Parameters.Add("@CALLNUMBER", System.Data.OleDb.OleDbType.VarChar, 255);
dbc.GetCommand().Parameters.Add("@TITLE", System.Data.OleDb.OleDbType.VarChar, 255);
dbc.GetCommand().Parameters.Add("@IMAGELOC", System.Data.OleDb.OleDbType.VarChar, 255);

dbc.GetCommand().Parameters["@CALLNUMBER"].Value = txtCallNumber.Text;
dbc.GetCommand().Parameters["@TITLE"].Value = txtTitle.Text;
dbc.GetCommand().Parameters["@IMAGELOC"].Value = (!moveto.Equals("db_storage\\") ? moveto : "db_storage\\no_img.png");

然后是:

dbc.GetCommand().ExecuteNonQuery();

接下来是我执行这段代码:

dbc.SetCommand("INSERT INTO publishing_info ([ID], [Author], [DateTime], [Publisher], [Pages], [ISBN_NO]) " +
               "VALUES (" +
               "SELECT([ID] FROM inventory " +
               "WHERE inventory.CallNumber=@CALLNUMBER AND inventory.Title=@TITLE AND inventory.ImageLocation=@IMAGELOC), " +
               "@AUTHOR, @DATETIME, @PUBLISHER, @PAGES, @ISBN);");

然后是:

dbc.GetCommand().ExecuteNonQuery();

以下是我供您参考的参数:

dbc.GetCommand().Parameters.Add("@AUTHOR", System.Data.OleDb.OleDbType.VarChar, 255);
dbc.GetCommand().Parameters.Add("@DATETIME", System.Data.OleDb.OleDbType.VarChar, 255);
dbc.GetCommand().Parameters.Add("@PUBLISHER", System.Data.OleDb.OleDbType.VarChar, 255);
dbc.GetCommand().Parameters.Add("@PAGES", System.Data.OleDb.OleDbType.UnsignedInt, 4);
dbc.GetCommand().Parameters.Add("@ISBN", System.Data.OleDb.OleDbType.VarChar, 255);

dbc.GetCommand().Parameters["@AUTHOR"].Value = txtAuthor.Text;
dbc.GetCommand().Parameters["@DATETIME"].Value = txtYear.Text;
dbc.GetCommand().Parameters["@PUBLISHER"].Value = txtPublisher.Text;
dbc.GetCommand().Parameters["@PAGES"].Value = uint.Parse(txtPages.Text);
dbc.GetCommand().Parameters["@ISBN"].Value = txtISBN.Text;

这是我的堆栈跟踪的屏幕截图(我无法附加它,因为我只有 1 个代表点) http://i44.tinypic.com/2w49t84.png

我应该怎么做才能使语法起作用?而且在执行另一个查询之前我是否需要先关闭连接?

更新 1

我曾经DMax(\"[ID]\", \"inventory\")检索最后一个ID,但它返回所有字段inventory并将其全部写入可以写入的字段,在我的 C# 代码中,但如果我在 MS Access 2010 上编写查询,它不会执行它在一个 C# 代码。似乎是什么问题?

更新 2

问题解决了dbc.GetCommand().Parameters.Clear()

4

1 回答 1

0

您不需要关闭连接,但您需要在子选择中插入左括号:

dbc.SetCommand("INSERT INTO publishing_info ([ID], [Author], [DateTime], [Publisher], [Pages], [ISBN_NO]) " +
           "VALUES (" +
           "(SELECT([ID] FROM inventory " +
           "WHERE inventory.CallNumber=@CALLNUMBER AND inventory.Title=@TITLE AND inventory.ImageLocation=@IMAGELOC), " +
           "@AUTHOR, @DATETIME, @PUBLISHER, @PAGES, @ISBN);");
于 2012-03-23T02:50:03.693 回答