我在访问table
database
现在我想从一个table
中选择并将它们插入另一个。
这是我的代码,但它在行Cmd.ExecuteNonQuery();
{"查询表达式中的语法错误(缺少运算符)' System.Object []'。"}
代码是:
public static void SetSelectedFeedIntoDB(Form2 frm2)
{
string StrCon = System.Configuration.ConfigurationManager.ConnectionStrings["FeedLibraryConnectionString"].ConnectionString;
OleDbConnection Connection = new OleDbConnection(StrCon);
OleDbDataAdapter DataA = new OleDbDataAdapter("Select * from FeedLibrary where ID=" + frm2.FeedSelectListBox.SelectedValue, Connection);
DataTable DTable = new DataTable();
DataA.Fill(DTable);
OleDbCommand Cmd = new OleDbCommand();
Cmd.Connection = Connection;
Connection.Open();
foreach (DataRow DR in DTable.Rows)
{
Cmd.CommandText = "insert into SelectedFeeds Values(" + DR.ItemArray + ")";
Cmd.ExecuteNonQuery();
}
Connection.Close();
}
我该怎么做才能解决这个问题?
答案 0 :(得分:5)
您的错误是由于您将DataRow的ItemArray属性连接到字符串这一事实引起的。在这种情况下,ItemArray(它是object []的一个实例)没有从其值自动生成字符串的方法,因此将类名返回为字符串" object []"但当然这会产生毫无意义的sql字符串
"insert into SelectedFeeds Values(object[])";
但你可以简单地构建一个SELECT .... INTO语句,在不使用DataTables和Adapters的情况下为你做任何事情
string cmdText = @"SELECT FeedLibrary.* INTO [SelectedFeeds]
FROM FeedLibrary
where ID=@id";
using(OleDbConnection Connection = new OleDbConnection(StrCon))
using(OleDbCommand cmd = new OleDbCommand(cmdText, Connection))
{
Connection.Open();
cmd.Parameters.Add("@id", OleDbType.Integer).Value = Convert.ToInt32( frm2.FeedSelectListBox.SelectedValue);
cmd.ExecuteNonQuery();
}
但是,SELECT ... INTO
语句会创建目标表,但如果目标表已存在则会出错。要解决这个问题,我们需要发现目标是否存在。如果它不存在,我们使用第一个SELECT ... INTO
查询,否则我们使用INSERT INTO ..... SELECT
// First query, this creates the target SelectedFeeds but fail if it exists
string createText = @"SELECT FeedLibrary.* INTO [SelectedFeeds]
FROM FeedLibrary
where ID=@id";
// Second query, it appends to SelectedFeeds but it should exists
string appendText = @"INSERT INTO SelectedFeeds
SELECT * FROM FeedLibrary
WHERE FeedLibrary.ID=@id";
using(OleDbConnection Connection = new OleDbConnection(StrCon))
using(OleDbCommand cmd = new OleDbCommand("", Connection))
{
Connection.Open();
// Get info about the SelectedFeeds table....
var schema = Connection.GetSchema("Tables",
new string[] { null, null, "SelectedFeeds", null});
// Choose which command to execute....
cmd.CommandText = schema.Rows.Count > 0 ? appendText : createText;
// Parameter @id is the same for both queries
cmd.Parameters.Add("@id", OleDbType.Integer).Value = Convert.ToInt32( frm2.FeedSelectListBox.SelectedValue);
cmd.ExecuteNonQuery();
}
这里我们有两个不同的查询,第一个像以前一样创建SelectedFeeds
表,第二个查询附加到该表中。
要发现目标表是否已经创建,我调用Connection.GetSchema来检索数据表(模式),如果表SelectedFeeds
存在则存在一行,如果没有这样的表则没有行。 />
此时,我使用正确的语句设置OleDbCommand来执行。