根据参数从数据库中检索数据

时间:2018-10-18 01:59:52

标签: sql-server asp.net-web-api

ValuesController.cs(发送HTTP请求,例如GET,POST,DELETE等):

public class ValuesController : ApiController
{
    Database_Access_Data.db dblayer = new Database_Access_Data.db();

    [HttpPost]
    [Route("api/Values/SendLocation")]
    public IHttpActionResult SendLocation([FromBody]Location cs)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            dblayer.SendLocation(cs);

            return Ok("Success");
        }
        catch (Exception e)
        {
            return Ok("Something went Wrong" + e);
        }
    }

    [HttpGet]
    [Route("api/Values/GetLocationHistory")]
    public DataSet GetLocationHistory()
    {
        DataSet ds = dblayer.GetLocationHistory();
        return ds;
    }

    [HttpPost]
    [Route("api/Values/SendDistance")]
    public IHttpActionResult SendDistance([FromBody]Location cs)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            dblayer.SendDistance(cs);

            return Ok("Success");
        }
        catch (Exception e)
        {
            return Ok("Something went Wrong" + e);
        }
    }

    [HttpGet]
    [Route("api/Values/GetUser")]
    public DataSet GetUser()
    {
        DataSet ds = dblayer.GetUser();
        return ds;
    }

    [HttpPost]
    [Route("api/Values/FlagingDevice")]
    public IHttpActionResult FlagingDevice([FromBody]Timer cs)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            dblayer.FlagingDevice(cs);

            return Ok("Success");
        }
        catch (Exception e)
        {
            return Ok("Something went Wrong" + e);
        }
    }

    [HttpPost]
    [Route("api/Values/SendBox")]
    public IHttpActionResult SendBox([FromBody]Box cs)
    {
        try
        {
            if (!ModelState.IsValid)
            {
                return BadRequest(ModelState);
            }

            dblayer.SendBox(cs);

            return Ok("Success");
        }
        catch (Exception e)
        {
            return Ok("Something went Wrong" + e);
        }
    }
}

db.cs(用于调用存储过程以及发送参数):

public class db
{
    SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["localhost"].ConnectionString);

    Location cs = new Location();

    public void SendLocation(Location cs)
    {
        SqlCommand com = new SqlCommand("SendGPS",con);
        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.AddWithValue("@DeviceImei", cs.DeviceImei);
        com.Parameters.AddWithValue("@Latitude",cs.Latitude);
        com.Parameters.AddWithValue("@Longitude",cs.Longitude);
        com.Parameters.AddWithValue("@Distance", cs.Distance);
        com.Parameters.AddWithValue("@LocationSend",cs.LocationSend);

        con.Open();
        com.Connection = con;

        com.ExecuteNonQuery();
        con.Close();
    }

    public DataSet GetLocationHistory()
    {
        SqlCommand com = new SqlCommand("GetLocationHistory", con);
        com.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);

        return ds;
    }

    public DataSet GetUser()
    {
        SqlCommand com = new SqlCommand("GetUser", con);
        com.CommandType = CommandType.StoredProcedure;

        SqlDataAdapter da = new SqlDataAdapter(com);
        DataSet ds = new DataSet();
        da.Fill(ds);

        return ds;
    }

    public void SendDistance(Location cs)
    {
        SqlCommand com = new SqlCommand("SendDistance", con);
        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.AddWithValue("@DeviceImei", cs.DeviceImei);
        com.Parameters.AddWithValue("@Distance", cs.Distance);
        com.Parameters.AddWithValue("@LocationSend", cs.LocationSend);

        con.Open();
        com.Connection = con;
        com.ExecuteNonQuery();
        con.Close();
    }

    public void FlagingDevice(Timer cs)
    {
        SqlCommand com = new SqlCommand("FlagingDevice", con);
        com.CommandType = CommandType.StoredProcedure;
        com.Parameters.AddWithValue("@Interval", cs.Interval);

        con.Open();
        com.Connection = con;
        com.ExecuteNonQuery();
        con.Close();
    }

    public void SendBox(Box cs)
    {
        SqlCommand com = new SqlCommand("SendBox", con);
        com.CommandType = CommandType.StoredProcedure;

        com.Parameters.AddWithValue("@Id", cs.Id);
        com.Parameters.AddWithValue("@PollingStationID", cs.PollingStationID);
        com.Parameters.AddWithValue("@DeviceImei", cs.DeviceImei);

        con.Open();
        com.Connection = con;
        com.ExecuteNonQuery();
        con.Close();
    }
}

用于从表中返回数据的存储过程:

     SET ANSI_NULLS ON
     GO
     SET QUOTED_IDENTIFIER ON
     GO

     ALTER PROCEDURE [dbo].[FlagingDevice]
         @Interval INT 
     AS 
         DECLARE @Time DATETIME

         IF @Interval = 5
         BEGIN 
             SET @Time = (SELECT MAX(LocationSend) FROM dbo.Location)

             SELECT D.imei, L.*, L1.*
             FROM Device D
             OUTER APPLY
                 (SELECT  * 
                  FROM dbo.Location L1
                  WHERE L1.DeviceImei = D.Imei 
                  GROUP BY DeviceImei, Latitude, Longitude, Distance, LocationSend
                  HAVING DATEDIFF(MINUTE, LocationSend, @Time) <= @Interval) AS L
             OUTER APPLY
                 (SELECT TOP 1 L4.ID AS 'Station', L3.Name
                  FROM [dbo].[ElectionDivision] L3, dbo.PollingStation L4
                  WHERE L.Latitude IS NOT NULL 
                    AND L.Longitude IS NOT NULL 
                    AND L.Distance IS NOT NULL 
                    AND L.DeviceImei = D.ImeI) AS L1
          END
          ELSE IF @Interval = 0
          BEGIN 
              SELECT D.imei, L.*, L1.*
              FROM Device D
              OUTER APPLY
                  (SELECT TOP 1 * 
                   FROM dbo.Location L1
                   WHERE L1.DeviceImei = D.Imei 
                   ORDER BY (LocationSend) DESC) AS L
              OUTER APPLY
                  (SELECT TOP 1 L4.ID AS 'Station', L3.Name
                   FROM [dbo].[ElectionDivision] L3, dbo.PollingStation L4
                   WHERE L.Latitude IS NOT NULL 
                     AND L.Longitude IS NOT NULL 
                     AND L.Distance IS NOT NULL 
                     AND L.DeviceImei = D.ImeI) AS L1
      END

更新:我正在使用sqldatareader,并将数据放入列表中,但不确定如何如valuecontroller类中所示返回FlaggingDevice方法。我应该在类或其他内容中创建列表吗?有什么建议吗?

        public List<FlagingDevice> FlagingDevice(FlagingDevice cs)
        {

            SqlCommand com = new SqlCommand("FlagingDevice", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Interval", cs.Interval);
            con.Open();
            com.Connection = con;
            using (SqlDataReader sqlDataReader = com.ExecuteReader())
            {

                int movieGenreIDIndex = sqlDataReader.GetOrdinal("DeviceImei");
                int movieIDIndex = sqlDataReader.GetOrdinal("Latitude");
                int genreIDIndex = sqlDataReader.GetOrdinal("Longitude");
                int genreIDIndex1 = sqlDataReader.GetOrdinal("Distance");
                int genreIDIndex2 = sqlDataReader.GetOrdinal("LocationSend");
                int genreIDIndex3 = sqlDataReader.GetOrdinal("Station");
                int genreIDIndex4 = sqlDataReader.GetOrdinal("Name");
                while (sqlDataReader.Read())
                {
                    student.Add(new FlagingDevice()
                    {
                        DeviceImei = sqlDataReader.IsDBNull(movieGenreIDIndex) ? null : sqlDataReader.GetString(movieGenreIDIndex),
                        Latitude = sqlDataReader.IsDBNull(movieIDIndex) ? null : sqlDataReader.GetString(movieIDIndex),
                        Longitude = sqlDataReader.IsDBNull(genreIDIndex) ? null : sqlDataReader.GetString(genreIDIndex),
                        Distance = sqlDataReader.IsDBNull(genreIDIndex1) ? null : sqlDataReader.GetString(genreIDIndex1),
                        LocationSend = sqlDataReader.IsDBNull(genreIDIndex2) ? null : Convert.ToString(sqlDataReader["LocationSend"]),
                        Name = sqlDataReader.IsDBNull(genreIDIndex4) ? null : sqlDataReader.GetString(genreIDIndex4)



                    });






                }
                sqlDataReader.Close();
                con.Close();
                return student;


            }




        }

0 个答案:

没有答案