protected void Build_Click(object sender, EventArgs e)
{
DataTable dt = new DataTable("number");
DataColumn c1 = new DataColumn("numberID", typeof(int));
DataColumn c2 = new DataColumn("value", typeof(string));
dt.Columns.Add(c1);
dt.Columns.Add(c2);
long baseValue = Convert.ToInt64(TextBox1.Text);
long topValue = Convert.ToInt64(TextBox2.Text);
Response.Write(baseValue.ToString());
for(long i=baseValue;i<topValue;i++)
{
DataRow r1 = dt.NewRow();
r1[0] = Convert.ToInt32(i);
r1[1] = i.ToString();
dt.Rows.Add(r1);
}
InsertTable(dt);
}
{
DataTable dt = new DataTable("number");
DataColumn c1 = new DataColumn("numberID", typeof(int));
DataColumn c2 = new DataColumn("value", typeof(string));
dt.Columns.Add(c1);
dt.Columns.Add(c2);
long baseValue = Convert.ToInt64(TextBox1.Text);
long topValue = Convert.ToInt64(TextBox2.Text);
Response.Write(baseValue.ToString());
for(long i=baseValue;i<topValue;i++)
{
DataRow r1 = dt.NewRow();
r1[0] = Convert.ToInt32(i);
r1[1] = i.ToString();
dt.Rows.Add(r1);
}
InsertTable(dt);
}
二、编写插入数据库的方法
public void InsertTable(DataTable table1)
{
string strInsert="insert into Number values (@value)";
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["connStr"]);
conn.Open();
SqlCommand com = new SqlCommand(strInsert, conn);
SqlParameter p1 = new SqlParameter("@value", SqlDbType.VarChar);
com.Parameters.Add(p1);
for(int i=0;i<table1.Rows.Count;i++)
{
DataRow row=table1.Rows[i];
p1.Value=row[1].ToString();
com.ExecuteNonQuery();
}
conn.Close();
}
通过编写这两个方法,基本的功能就已经实现,不过其间存在一个致命的性能问题,在数据量在相当大的情况下效率会相当的低,所以在Sql Server批量插入数据时(特别是有规律可寻的大数据面前),我们多采用存储过程的方式优化其性能。{
string strInsert="insert into Number values (@value)";
SqlConnection conn = new SqlConnection(ConfigurationManager.AppSettings["connStr"]);
conn.Open();
SqlCommand com = new SqlCommand(strInsert, conn);
SqlParameter p1 = new SqlParameter("@value", SqlDbType.VarChar);
com.Parameters.Add(p1);
for(int i=0;i<table1.Rows.Count;i++)
{
DataRow row=table1.Rows[i];
p1.Value=row[1].ToString();
com.ExecuteNonQuery();
}
conn.Close();
}
CREATE PROCEDURE up_number_ins
AS
DECLARE @base int
DECLARE @top int
SET @top=1000
SET @base=10
WHILE @base<@top
BEGIN
INSERT INTO number VALUES (@base)
SET @base=@base+1
END
GO
以上代码在针对系统生成指定数据段时,效率相对于前面而言要高出N倍,其具体使用时还得看应用环境和问题,具体问题具体分析,这才是我的实战理论哈AS
DECLARE @base int
DECLARE @top int
SET @top=1000
SET @base=10
WHILE @base<@top
BEGIN
INSERT INTO number VALUES (@base)
SET @base=@base+1
END
GO