将用户的新信息插入数据库一般是写一个insert 语句。 这里我们利用的是SqlDataAdapter的Update方法。
---------------------
1:首先共同的SqlHelper类中有如下静态方法:
-----------------------------------------------------------------
public static void Update(string connectionString, CommandType cmdType, string cmdText, DataTable srcDataTable)
{
try
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
SqlCommand comm = new SqlCommand();
comm.Connection = conn;
comm.CommandText = cmdText;
comm.CommandType = cmdType;
comm.CommandTimeout = 300;
SqlDataAdapter adapter = new SqlDataAdapter(comm);
SqlCommandBuilder buider = new SqlCommandBuilder(adapter);
buider.ConflictOption = ConflictOption.OverwriteChanges;
buider.RefreshSchema();
adapter.DeleteCommand = buider.GetDeleteCommand(true);
adapter.InsertCommand = buider.GetInsertCommand(true);
adapter.UpdateCommand = buider.GetUpdateCommand(true);
adapter.Update(srcDataTable);
}
}
catch (Exception ex)
{
throw ex;
}
}
-----------------------------------------------------------------
这段代码毋庸置疑,关键是我在调用后始终数据库中没有数据 原因何在呢?
先看我之前的代码段:
--------------------------
private const string F_SQL_USER_UPDATE="select * from user";
public void InsertUser(DataTable refData)
{
try
{
SqlHelper.Update(SqlHelper.ConnString, CommandType.Text, F_SQL_USER_UPDATE, refData);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
-------------------------------------------------------------
问题出在没有对传入的参数refData给予是新增还是修改的标识
如下修改即可:
--------------------------
private const string F_SQL_USER_UPDATE="select * from user";
public void InsertUser(DataTable refData)
{
try
{
//若新增
refData.Row[0].SetAdded();
//if update please refData.Row[0].SetModified();
SqlHelper.Update(SqlHelper.ConnString, CommandType.Text, F_SQL_USER_UPDATE, refData);
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
-------------------------------------------------------------