⾦蝶K3Cloud中DBUtils的⽤法
Execute⽅法⽤于不需要返回数据的执⾏语句,如DDL、UPDATE、DELETE语句。返回值为影响的⾏数。 Execute⽅法每次仅执⾏⼀条语句,对SQLServer⽀持多条语句⼀起执⾏,因此多条语句拼在⼀起执⾏没有问题,但Oracle下执⾏会报错。 如果需要执⾏多条语句,请调⽤批量执⾏⽅法:ExecuteBatch。 如果要执⾏SELECT语句,建议使⽤ExecuteReader⽅法。
执⾏DDL:
C#
DBUtils.Execute(context, "CREATE TABLE T_TEMP(FID INT NOT NULL, FNAME VARCHAR(10) NULL ) ");
以下语句未使⽤参数化,会导致数据库硬解析影响性能。
C#
foreach (FieldValue val in fieldValues)
{
string sql = string.Format("UPDATE T_DEMO set FValue = {0} where FID = {1} ", val.Value, val.Id); //注意此处val.Value不
应该拼接,应使⽤参数化
DBUtils.Execute(Context, sql);
}
执⾏带参数的语句:
C#
sql = "INSERT INTO t_temp(FId, FType, FKernelXml, FName, FDevType) VALUES (@FId, @FType, @FKernelXml, @FName,
@FDevType)";
List<SqlParam> paramList = new List<SqlParam>();
paramList.Add(new SqlParam("@FId", KDDbType.AnsiString, formID)); //⾮unicode(varchar类型)
paramList.Add(new SqlParam("@FType", KDDbType.Int64, metadata.Type));
paramList.Add(new SqlParam("@FKernelXml", KDDbType.Xml, xml));
paramList.Add(new SqlParam("@FName", KDDbType.String, metadata.Name)); //unicode字符(nvarchar类型)
paramList.Add(new SqlParam("@FDevType", KDDbType.Int32, (int)metadata.DevType));
DBUtils.Execute(this.Context, sql, paramList);
file:///C:/Users/rd_weixy/AppData/Local/Temp/msohtmlclip1/01/clip_image001.png ExecuteDynamicObject
执⾏指定的SQL并返回默认的⼀批使⽤DynamicObject集合描述的数据。
注:该⽅法内部是调⽤ExecuteDataReader,如果不是必须返回DynamicObject类型,建议使⽤ExecuteDataReader更好。
下⾯例⼦将获取的DynamicObject对象填充到单据体中。
C#
//在表单插件中,应调⽤服务接⼝来获取数据,不能直接访问App服务
DynamicObjectCollection dcObjs = DBServiceHelper.ExecuteDynamicObject(this.View.Context, sql, null, null,
sql中delete用法System.Data.CommandType.Text, param);
//获取单据体数据包
DynamicObjectCollection dyCollection = (DynamicObjectCollection)this.View.Model.DataObject[EitityKey]; dyCollection.Clear();
DynamicObject dyObj;
foreach (var obj in dcObjs)
{
dyObj = (DynamicObject)dyCollection.DynamicCollectionItemPropertyType.CreateInstance();
dyObj["FDataCenterId"] = obj["FDataCenterId"];
dyObj["FDCNumber"] = obj["FNumber"];
dyObj["FDCName"] = obj["FName"];
if (!string.IsNullOrWhiteSpace(_currentDataCenterId) && dyObj["FDataCenterId"].Equals(_currentDataCenterId)) {
dyObj["FStatus"] = Kingdee.BOS.Resource.ResManager.LoadKDString("启⽤", "002014030004624", Kingdee.BOS.Resource.SubSystemType.BOS);
_isEnable = true;
}
else
{
dyObj["FStatus"] = "";
}
dyCollection.Add(dyObj);
}
服务接⼝使⽤的DynamicObject类型时,⽤ExecuteDynamicObject⽅法取数更⽅便,不需要⾃⼰转换。C#
string sql = @"select FUserID, FName, FFORBIDSTATUS FROM t_sec_user ";
DynamicObjectCollection charts = DBUtils.ExecuteDynamicObject(ctx, sql);
...
ISaveService saveService = App.ServiceHelper.GetService<ISaveService>();
saveService.Save(ctx, charts.ToArray<DynamicObject>());
以下例⼦ExecuteDynamicObject应该⽤ExecuteDataReader更合适:
C#
List<long> orgList = new List<long>();
string sql = "SELECT FCreateOrgId FROM t_org_bdctrlpolicy WHERE FBaseDataTypeId = @formId ";
SqlParam[] paramList = new SqlParam[1];
paramList[0] = new SqlParam("@formId", DbType.String, formId);
DynamicObjectCollection collections = DBUtils.ExecuteDynamicObject(ctx, sql, paramList: paramList);
foreach (DynamicObject dr in collections)
{
//此处⽤不到DynamicObject特性,不应该⽤ExecuteDynamicObject⽅法
orgList.Add(Convert.ToInt64(dr["FCreateOrgId"]));
}
使⽤ExecuteDynamicObject获取实体类数据,按实体类定义的属性获取。
C#
/// ⽤户的实体类
[Serializable, DataEntityType(Alias = "t_sec_user")]
public class User : DynamicObjectView
{
/// <summary>KDUser的动态类型</summary>
public static readonly DynamicObjectType UserType = new DynamicObjectType(
"User",
attributes: new DataEntityTypeAttribute() { Alias = "t_sec_user" }
);
public User(DynamicObject obj) : base(obj) { }
public static User Create()
{
User kdUser = new User(new DynamicObject(UserType));
return kdUser;
}
/// <summary>⽀持从DynamicObject隐式转化到KDUser类型</summary>
/// <param name="obj">要隐式转换的动态实体</param>
/// <returns>新构建的KDUser对象</returns>
public static implicit operator User(DynamicObject obj)
{ return new User(obj); }
#region FUserID User的主键
/// <summary>FUserID的属性描述符</summary>
public static DynamicProperty UserIDProperty = UserType.RegisterSimpleProperty("UserID", typeof(int), attributes: new SimplePropertyAttribute(true) { Alias = "FUserID" });
/// <summary>
/// 返回/设置 FUserID的主键
/// </summary>
public int UserID
{
get { return (int)UserIDProperty.GetValue(this.DataEntity); }
set { UserIDProperty.SetValue(this.DataEntity, value); }
}
#endregion
//⽤户实体的其他属性
...
}
//调⽤⽰例:
//通过User.UserType获取User实体对象
string sql = @"select FUserID, FName, FFORBIDSTATUS FROM t_sec_user where FUserID = @FUserID"; //与实体定义中的属性匹配,否则对应的实体属性会为空
DynamicObjectCollection userCollection = DBUtils.ExecuteDynamicObject(ctx, sql, User.UserType, paramList: new SqlParam[] { new SqlParam("@FUserID", DbType.Int64, ctx.UserId) });
User user = userCollection[0];
file:///C:/Users/rd_weixy/AppData/Local/Temp/msohtmlclip1/01/clip_image001.png ExecuteReader
执⾏指定的SQL并返回DataReader数据。
⽀持KSQL语法,若要执⾏SQLServer或Oracle语法,请在语句前加⽅⾔标识/*dialect*/。
1. 批量查询
⽅法:
IDataReader ExecuteReader(Context ctx, BatchSqlParam param, string selectFieldSql, string where = "")
⽤于不同参数批量取数,例如:
参数说明:
BatchSqlParam - 批量参数(批量执⾏参数。仅⽤于单表批量执⾏,where只⽀持简单And逻辑)
BatchSqlParam类说明如下:
C#
/// <summary>
/// 表名和更新的数据。sqlserver数据库dt的列名将做为临时表列名
/// </summary>
/// <param name="tableName">要操作的表名(查询时是查询的主表,即from的表)</param>
/// <param name="dt">需要批量查询、更新、删除的数据</param>
/// <param name="createTempTableSQL">创建临时表sql,字段名必须与dt列名⼀致(仅在sqlserver使⽤,可不指定,默认只⽀持Varchar(200),decimal(23,10), bigint, datetime )</param>
BatchSqlParam(string tableName, DataTable dt, string createTempTableSQL = "")
/// <summary>
/// update语句Set字段
/// </summary>
/// <param name="columnName">列名,必须与DataTable列名匹配</param>
/// <param name="dbType">参数类型</param>
/// <param name="fieldName">真实字段名(要set的字段)</param>
/// <param name="value"></param>
AddSetExpression(string columnName, KDDbType dbType, string fieldName)
/// <summary>
/// where条件,只⽀持And逻辑
/// </summary>
/// <param name="columnName">列名,必须与DataTable列名匹配</param>
/// <param name="dbType">参数类型</param>
/// <param name="fieldName">真实字段名</param>
/// <param name="tableAliases"></param>
AddWhereExpression(string columnName, KDDbType dbType, string fieldName, string tableAliases = "")
/// <summary>
/// Join 语句
/// </summary>
/// <param name="joinExpr">完整join语句,例如: "left join t_bas_Object t2 on t1.fid = t2.fid " </param> AddJoinExpression(string joinExpr)
调⽤⽰例如下:
C#
DataTable dt = new DataTable();
dt.Columns.Add("f1");
DataRow row = dt.NewRow();
row[0] = 16394;
dt.Rows.Add(row);
row = dt.NewRow();
row[0] = 80043;
dt.Rows.Add(row);
//BatchSqlParam构造函数TableName为 from 的表名
BatchSqlParam batchParam = new BatchSqlParam("T_BAS_OPERATELOG", dt);
batchParam.TableAliases = "t1";
batchParam.AddWhereExpression("f1", KDDbType.Int32, "FUSERID", "t1");
batchParam.AddJoinExpression("inner join t_sec_user t2 on t1.fuserid = t2.fuserid");
using (IDataReader dr = DBUtils.ExecuteReader(ctx, batchParam, "t1.FID, t1.FUserId, t2.FName", " t1.flogonorgid = 1 ")) {
while (dr.Read())
{
object obj = dr[0];
object userid = dr[1];
object name = dr[2];
}
}
以上执⾏的语句:
SELECT t1.FID, t1.FUserId, t2.FName FROM T_BAS_OPERATELOG t1 inner join t_sec_user t2 on t1.fuserid = t2.fuserid where t1.FUSERID = :f1 and t1.flogonorgid = 1
注意:
Datatable的列名"f1"必须与AddWhereExpression的参数"f1"⼀致。
2. 执⾏语句:
Overload Description
流⽅式读SQL查询结果
返回DataReader,指定命令类型
返回DataReader,指定参数
返回DataReader,指定参数和命令类型
返回DataReader,指定多个参数
返回DataReader,指定多个参数和命令类型
⽰例:
根据id取⽤户参数。
C#
List<SqlParam> paramList = new List<SqlParam>();
string sql = @"SELECT FKEY, FUSERID, FPARAMETERS FROM T_BAS_USERPARAMTER WHERE FID = @Fid"; paramList.Add(new SqlParam("@FId", DbType.AnsiString, sid));
using (IDataReader rs = DBUtils.ExecuteReader(Context, sql, paramList))
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论