Retrieve ODBC table and Insert into SQL Server CE database

僤鯓⒐⒋嵵緔 提交于 2019-12-07 12:25:51

问题


I have an ODBC connection to a database of which I need one table of data. The table has about 20 rows, and a couple thousand lines of data.

I intend to insert this table into my local SQL Server CE database, where I can put it to further use. Both connections have been tested and work.

My attempt was at just inserting one column to keep things simple (I'm new to C#, programming, and stackoverflow).

OdbcConnection c = new OdbcConnection(ConnectionString1);
SqlCeConnection d = new SqlCeConnection(ConnectionString2);

c.Open();
d.Open();

string sqlC = "SELECT * FROM ODBCTABLE WHERE ODBCCOLUMN='12345'";
OdbcCommand commandC = new OdbcCommand(sqlC, c);

string sqlD = "INSERT INTO SQLCETABLE(SQLCECOLUMN) VALUES (@sql)";
SqlCeCommand commandD = new SqlCeCommand(sqlD, d);

OdbcDataReader reader = commandC.ExecuteReader();

while (reader.Read())
{
  string x = reader[0].ToString();                   
  commandD.Parameters.Add("@sql",SqlDbType.NVarChar, 5).Value = x;
  commandD.ExecuteNonQuery();     
}

c.Close();
c.Dispose();

d.Close();
d.Dispose();

I get the error The SqlCeParameter with this name is already contained by this SqlCeParameterCollection.

  1. Why is this wrong?
  2. Is there a way to fix this?
  3. Are there better ways to do this transfer? (I believe sqlbulktransfer does not exist for odbc)
  4. Being my first post on Stackoverflow, did I go about posting a question correctly?

回答1:


Change this part of your code

commandD.Parameters.Add("@sql",SqlDbType.NVarChar, 5); 
while (reader.Read()) 
{ 
  string x = reader[0].ToString();                   
  commandD.Parameters["@sql"].Value = x ;
  commandD.ExecuteNonQuery();      
} 

The problem arises because, in every loop, you repeat the add of the same named parameter to the collection resulting in the error above.
Moving the creation of the parameter outside the loop and updating only the value inside the loop should resolve the error.

Yes, I think you have posted the question correctly.



来源:https://stackoverflow.com/questions/12289832/retrieve-odbc-table-and-insert-into-sql-server-ce-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!