1.创建存储过程
CREATE DEFINER=`root`@`%` PROCEDURE `SearchProduct`(
IN theSort VARCHAR(500), --参数1
IN queryContent VARCHAR(500), --参数2
IN theSourceId INT, --参数3
IN pageIndex INT, --参数4
IN pageSize INT --参数5
)
BEGIN
IF queryContent IS NOT NULL THEN
set @theSql = CONCAT('SELECT DISTINCT a.Id,a.Name,a.ShortDescription,d.PictureId,e.Amount,a.FeatureType,
(
',theSort,'
) as namesort
FROM t_product a
INNER JOIN t_product_display b ON a.Id = b.ProductId
LEFT JOIN t_product_label c on a.Id = c.ProductId
LEFT JOIN t_product_picture d ON a.Id = d.ProductId
INNER JOIN t_product_price e ON a.Id = e.ProductId
WHERE a.Deleted = 0
AND b.SourceSettingId = ',theSourceId,'
AND d.SourceSettingId = ',theSourceId,'
AND e.SourceSettingId = ',theSourceId,'
AND (b.WXPublished = 1 AND (b.AllowStartDateUtc IS NULL OR NOW() > b.AllowStartDateUtc) AND (b.AllowEndDateUtc IS NULL OR NOW() < b.AllowEndDateUtc))
AND (',queryContent,')
And d.Id = (SELECT Id FROM t_product_picture WHERE(ProductId = a.Id And `Status` = 1 AND SourceSettingId = ',theSourceId,') ORDER BY IsFeatured DESC,DisplayOrder ASC,Id ASC LIMIT 1) order by namesort desc,Id LIMIT ',pageIndex,',',pageSize);
END IF;
prepare stmt from @theSql;
execute stmt;
END
2.创建数据库连接
using MySql.Data.MySqlClient;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace BJ.Mall.Services
{
public class DataAccess
{
static String mysqlStr = ConfigurationManager.AppSettings["MySqlService"].ToString();
static MySqlConnection mysql = new MySqlConnection(mysqlStr);
static MySqlCommand com = new MySqlCommand();
public DataSet selectProc(string storedProcName, IDataParameter[] parameters)
{
DataSet dt = new DataSet();
try
{
if (mysql.State != ConnectionState.Open)
mysql.Open();
com.Connection = mysql;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = storedProcName;
com.Parameters.AddRange(parameters);
MySqlDataAdapter mda = new MySqlDataAdapter(com);
mda.Fill(dt);
mysql.Close();
}
catch (Exception er)
{
}
finally
{
//关闭连接,释放空间.
if (mysql.State == ConnectionState.Open)
mysql.Close();
mysql.Dispose();
com.Parameters.Clear();
com.Dispose();
}
return dt;
}
}
}
3.在Web.config文件中配置数据库连接
<add key="MySqlService" value="server=rm-wz91e3xxx6fz11qo.mysql.rds.aliyuncs.com;port=3306;User Id=root;password=xxx;Database=xxx" />
4.调用存储过程
theSql += "a.Name LIKE '%" + word + "%' OR c.Name LIKE '%" + word + "%' OR ";
theSort += "(case when (a.Name LIKE '%" + word + "%') then 1 else 0 end)+";
if (string.IsNullOrEmpty(theSql) && string.IsNullOrEmpty(theSort))
return Json(null, JsonRequestBehavior.AllowGet);
theSql = theSql.Substring(0, theSql.Length - 4); //参数1
theSort = theSort.Substring(0, theSort.Length - 1);//参数2
DataAccess dataAccess = new DataAccess();
var current = CurrentAuthentication.GetLogInCurrentCustomer();
var sourceSettingId = current.SourceSettingId;
IDataParameter[] mySqlParams = new IDataParameter[]
{
new MySqlParameter(){ ParameterName = "theSort", DbType = DbType.StringFixedLength, Value = theSort },
new MySqlParameter(){ ParameterName = "queryContent", DbType = DbType.StringFixedLength, Value = theSql },
new MySqlParameter(){ ParameterName = "theSourceId",DbType = DbType.Int32,Value = sourceSettingId },
new MySqlParameter(){ ParameterName = "pageIndex",DbType = DbType.Int32,Value = pageIndex },
new MySqlParameter(){ ParameterName = "pageSize",DbType = DbType.Int32,Value = pageSize },
};
DataSet dt = dataAccess.selectProc("SearchProduct", mySqlParams);
if (!(dt.Tables[0] != null))
{
return Json(null, JsonRequestBehavior.AllowGet);
}
var dataTabel = dt.Tables[0];
var model = new SearchProductListModel();
var areaName = string.Format("{0}{1}", current.PlatformType.ToUpper(), current.SourceSettingKey.ToUpper());
if (dataTabel.Rows.Count > 0)
{
for (int i = 0; i < dataTabel.Rows.Count; i++)
{
var item = dataTabel.Rows[i];
long pictureId = 0;
string promotionTitle = string.Empty;
var product = new Product();
var linkUrl = Url.Action("ProductDetail", "Product", new { area = areaName, id = Convert.ToInt32(item["Id"]) });
product = this._productService.GetProductById(Convert.ToInt32(item["Id"]));
PromotionProductCommon productCommon = null;
var isActive = this._productService.IsExistProductDisplayByProductId(product.Id, current.SourceSettingId);
if (product.ProductType == (int)ProductTypeEnum.CommonProduct)
productCommon = PromotionExtensions.GetPromotionProductCommonByProduct(product);
var productPrice = product.ProductPrices().Where(x => x.SourceSettingId == current.SourceSettingId).FirstOrDefault();
if (isActive && productCommon != null)
{
pictureId = productCommon.PromotionPictureId;
promotionTitle = productCommon.PromotionTitle;
}
model.SearchProductItem.Add(new SearchProductModel()
{
Name = item["Name"].ToString(),
Id = Convert.ToInt32(item["Id"]),
ShortDescription = item["ShortDescription"].ToString(),
DefaultPictureUrl = pictureId > 0 ? this._commonService.GetPictureUrl(pictureId) : this._commonService.GetPictureUrl(Convert.ToInt32(item["PictureId"])),
LinkUrl = linkUrl,
FeatureType = Convert.ToInt32(item["FeatureType"]),
PromotionTitle = promotionTitle != null ? promotionTitle : null,
Amount = Convert.ToDecimal(item["Amount"]).ToString("¥#0.00")
});
}
}