将数据集到Oracle表 [英] Insert Data Set into Oracle Table
问题描述
我想从我的数据表中的所有记录插入到Oracle表。我已经想通了如何将一个记录,但是我怎么去插入多条记录。这里最大的问题是,在数据列的顺序不匹配,Oracle表列的顺序。
下面是我使用插入一条记录代码
CMD的OdbcCommand =新的OdbcCommand();
试
{
cmd.Connection = getDBConnection(); //这个调用只会越来越b cmd.CommandType = CommandType.Text连接到数据库$ B $另一种方法;
cmd.CommandText =INSERT INTO MY_INSERT_TEST(NAME)VALUES(\'Test 1\');
cmd.ExecuteNonQuery();
cmd.Connection.Close();
cmd.Dispose();
}
抓
{
cmd.Connection.Close();
cmd.Dispose();
}
让我怎么修改这些从数据添加所有记录集<? / p>
假设你要循环行的集合,要插入所有的人,那么我会像一个伪尝试这
字符串声明cmdtext =INSERT INTO MY_INSERT_TEST(COL1,col2的,COL3)VALUES(?,?,?);使用(OdbcConnection CN = getDBConnection())
使用
(CMD的OdbcCommand =新的OdbcCommand(声明cmdtext,CN))
{
cn.Open();
cmd.Parameters.AddWithValue(@ P1,);
cmd.Parameters.AddWithValue(@ P2,);
cmd.Parameters.AddWithValue(@ P3,);
的foreach(在dt.Rows的DataRow R)
{
cmd.Parameters [@ P1]值= R [栏3]的ToString())。;
cmd.Parameters [@ P2]值= R [列1]的ToString());
cmd.Parameters [@ P3]值= R [列2]的ToString());
cmd.ExecuteNonQuery();
}
}
建立一个参数化查询,定义参数(此处字符串类型的所有参数,需要进行检查),然后遍历DataTable的分配由相应列的参数值的行。请注意,在命令文本你不直接写值,但你把为将要在循环内提供实际值的占位符。
I am trying to insert all the records from my data table into oracle table. I have figured out how to insert a single record, however how do I go about inserting multiple records. The biggest problem here is that the order of columns in dataset does not match the order of columns in oracle table.
Here is the code I am using to insert a single record:
OdbcCommand cmd = new OdbcCommand();
try
{
cmd.Connection = getDBConnection(); //This calls another method that just gets the connection to database
cmd.CommandType = CommandType.Text;
cmd.CommandText = "INSERT INTO MY_INSERT_TEST(NAME) VALUES(\'Test 1\')";
cmd.ExecuteNonQuery();
cmd.Connection.Close();
cmd.Dispose();
}
catch
{
cmd.Connection.Close();
cmd.Dispose();
}
so how do I modify these to add all records from the data set?
Supposing you want to loop over a collection of rows and you want to insert all of them then I would try with a pseudocode like this.
string cmdText = "INSERT INTO MY_INSERT_TEST(Col1, Col2, Col3) VALUES(?, ?, ?)";
using(OdbcConnection cn = getDBConnection())
using(OdbcCommand cmd = new OdbcCommand(cmdText, cn))
{
cn.Open();
cmd.Parameters.AddWithValue("@p1", "");
cmd.Parameters.AddWithValue("@p2", "");
cmd.Parameters.AddWithValue("@p3", "");
foreach(DataRow r in dt.Rows)
{
cmd.Parameters["@p1"].Value = r["Column3"].ToString());
cmd.Parameters["@p2"].Value = r["Column1"].ToString());
cmd.Parameters["@p3"].Value = r["Column2"].ToString());
cmd.ExecuteNonQuery();
}
}
Build a parameterized query, define the parameters (here are all parameters of string type, need to be checked) and then loop over the rows of the datatable assigning the parameters value from the corresponding column. Notice that in the command text you don't write directly the values but you put a placeholder for the actual value that you will supply inside the loop.
这篇关于将数据集到Oracle表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!