如何用C#把数据集写进数据库?
我通过运算形成了一个完整的数据表DataTable dt,但是,现在我该如何把该表添加到现有数据库的tx表里面呢?(目前tx表只有表结构,没有记录)
------解决方案--------------------protected void btnSave_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//除了验证控件,我又写了一个函数处理额外的验证
if (CheckValid() == false)
{
return;
}
//0永远不可能大于1,所以实际上这条SQL是取不到数据的,不过我只是借助它建立表结构罢了
string sql = "SELECT * FROM OfficeUseBusRecord WHERE 0> 1 ";
SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings[ "TedabusMIS "].ToString());
SqlDataAdapter sda = new SqlDataAdapter(sql, conn);
SqlCommandBuilder scb = new SqlCommandBuilder(sda);
DataSet ds = new DataSet();
sda.Fill(ds);
//这里,就可以借助数据表的NewRow方法获得一个新的数据行,其中包含了列的信息
DataRow dr = ds.Tables[0].NewRow();
dr[ "DeptID "] = GetCurrentUserDeptID();
dr[ "PersonName "] = txtUsePerson.Text;
dr[ "UserBusDate "] = DateTime.Parse(txtDate.Text);
dr[ "StartPos "] = txtStartPos.Text;
dr[ "DestPos "] = txtDestPos.Text;
dr[ "Reason "] = txtReason.Text;
ds.Tables[0].Rows.Add(dr);
//SqlDataAdapter的Update方法返回更新的数据条数,我用这个判断更新是否成功
if (sda.Update(ds) > 0)
{
RegisterStartupScript( "message ", " <script language= 'JavaScript '> alert( '添加成功 '); </script> ");
}
else
{
RegisterStartupScript( "message ", " <script language= 'JavaScript '> alert( '添加失败 '); </script> ");
}
}
}
------解决方案--------------------//DataTable中插入几个值
DataTable dt=new DataTable ();
DataColumn column=new DataColumn ( "sid ",typeof (System .Int32 ));
dt .Columns .Add (column );
column = new DataColumn( "sname ", typeof(System.String));
dt.Columns.Add(column);
dt.Rows.Add(1, "aaa ");
dt.Rows.Add(2, "bbb ");
//更新到数据库中
SqlConnection con = new SqlConnection( "server=.;database=student;uid=sa;pwd=0421 ");
SqlDataAdapter sda = new SqlDataAdapter( "select * from studentInfor ", con);
SqlCommandBuilder buider = new SqlCommandBuilder(sda);
DataTable st = new DataTable();
sda.Fill(st);
foreach (DataRow row in dt.Rows )
{
st.Rows.Add(row[0],row [1]);
}
sda.Update(st);
------解决方案--------------------数据库的存储过程PROC
你在数据库中仿照写一个
然后在代码中与数据库沟通时,调用你写的PROC
set ANSI_NULLS ON
set QUOTED_IDENTIFIER ON
go
ALTER PROCEDURE [dbo].[ProcInsertTArea]
(
@AreaName nvarchar(50),
@ParentAreaID int,
@Description nvarchar(50),
@PK int output
)
AS
SET NOCOUNT OFF;
INSERT INTO TArea (AreaName, ParentAreaID,Description)
VALUES (@AreaName, @ParentAreaID,@Description);
SET @PK= SCOPE_IDENTITY()
return @PK