using System;
using System.Windows .Forms ;
using System.Data ;
using System.Data.SqlClient ;
namespace Dbcommonoperate
{
/// <summary>
/// Class1 的摘要说明。
/// </summary>
public class Dboperate
{
private SqlConnection conn;
private DataSet tempds;
private DataTable tempdt;
private SqlDataAdapter sadapter;
private SqlCommand cmd;
public Dboperate()
{
//
// TODO: 在此处添加构造函数逻辑
//
tempds=new DataSet ();
tempdt=tempds.Tables .Add ();
}
public bool ExecuteData(DataTable objtable)
{
bool flag=false;
int intRowsAffected=0;
SqlCommand cmdInsert=CreateInsertCommand();
SqlCommand cmdUpdate=CreateUpdateCommand();
SqlCommand cmdDelete=CreateDeleteCommand();
DataViewRowState state=DataViewRowState.Added |DataViewRowState.Deleted |DataViewRowState.ModifiedCurrent ;
foreach(DataRow row in objtable.Select ("","",state))
{
switch (row.RowState )
{
case DataRowState.Added :
intRowsAffected=SubmitInsert(row,cmdInsert);
break;
case DataRowState.Deleted :
int RowsAffected=SubmitDelete(row,cmdDelete);
break;
case DataRowState.Modified :
intRowsAffected=SubmitUpdate(row,cmdUpdate);
break;
}
if(intRowsAffected==1)
{
row.AcceptChanges ();
flag=true;
}
else
{
MessageBox.Show ("Update attempt filed");
}
}
return flag;
}
private SqlCommand CreateInsertCommand()
{
string strsql="insert into Student values( '@Stu_ID','@Stu_Name','@Stu_Sex','@Stu_Dem','@Stu_Home')";
SqlCommand cmdInsert=new SqlCommand (strsql,conn);
SqlParameterCollection pc=cmdInsert.Parameters ;
pc.Add ("@Stu_ID",SqlDbType.Char ,3,"Stu_ID");
pc.Add ("@Stu_Name",SqlDbType.Char ,15,"Stu_Name");
pc.Add ("@Stu_Sex",SqlDbType.Char ,2,"Stu_Sex");
pc.Add ("@Stu_Dem",SqlDbType.Char ,10,"Stu_Dem");
pc.Add ("@Stu_Home",SqlDbType.Char, 10,"Stu_Home");
return cmdInsert;
}
private int SubmitInsert(DataRow row,SqlCommand cmd)
{
SqlParameterCollection pc;
int n=0;
try
{
pc=cmd.Parameters ;
pc["@Stu_ID"].Value = row["Stu_ID"];////转换不过来,错误就在这儿,通过监视发现返回的
pc["@Stu_Name"].Value =row["Stu_Name"];//为string
pc["@Stu_Sex"].Value =row["Stu_Sex"];
pc["@Stu_Dem"].Value =row["Stu_Dem"];
pc["@Stu_Home"].Value =row["Stu_Home"];
n= cmd.ExecuteNonQuery ();
}
catch (Exception err)
{
MessageBox.Show (err.Message ,"错误",MessageBoxButtons.OK ,MessageBoxIcon.Warning );
}
return n;
}
private SqlCommand CreateUpdateCommand()
{
SqlCommand cmd=new SqlCommand ();
return cmd;
}
private int SubmitUpdate(DataRow row,SqlCommand cmd)
{
return cmd.ExecuteNonQuery ();
}
private SqlCommand CreateDeleteCommand()
{
SqlCommand cmd=new SqlCommand ();
return cmd;
}
private int SubmitDelete(DataRow row,SqlCommand cmd)
{
return cmd.ExecuteNonQuery ();
}
}
}
这是我写的一个数据库公共类,我在程序里用了datagrid显示,并可以在datagrid里进行修改,将修改后的结果进行更新,可是出现了转换错误,想不起来该用什么方法,请高手指教一下。