简体   繁体   English

输入字符串的格式不正确。 使用 MYSQL

[英]Input string was not in a correct format. using MYSQL

I had a code that was working the past few weeks and am getting an ERROR "Input string was not in a correct format"我有一个过去几周一直在工作的代码,但收到一个错误“输入字符串的格式不正确”

NB:(MVC Asp.net)注意:(MVC Asp.net)

the view gets data from the Razor page URL and Execute a query视图从 Razor 页面 URL 获取数据并执行查询

the URL is like this: https://localhost:44348/Devices/Details/5?typeName=Dongle URL 是这样的: https://localhost:44348/Devices/Details/5?typeName=Dongle

and the following the View code:以及以下查看代码:

    public ActionResult Details(string typeName, int? id)
    {
        var sql = "SELECT A.*," +
             " COALESCE(ps.first_name, '') as firstname," +
             " COALESCE(ps.last_name, '') as lastname," +
             " COALESCE(p.program_name, '') as program_Name, " +
             " COALESCE(l.loan_date, '') as loan_date, " +
             " COALESCE(l.return_date, '') as return_date" +
             " FROM devices A" +
             " LEFT JOIN device_loans l on l.device_id = A.device_id" +
             " LEFT JOIN persons ps on ps.person_id = l.person_id" +
             " LEFT JOIN programs p on A.program_id = p.program_id" +
             " WHERE A.device_type = '" + typeName + "' and p.program_id = "+ id +";";

        var devices = _context.DeviceDetails
            .FromSqlRaw(sql)
            .ToList();

        return View(devices);
    }

I have tried Passing parameters with parameter placeholders but still not working我已经尝试使用参数占位符传递参数但仍然无法正常工作

please help.请帮忙。

Because your parameter id: is nullable, you need combine sql like:因为您的参数 id: 可以为空,所以您需要组合 sql ,例如:

var sql = "SELECT A.*," +
     " COALESCE(ps.first_name, '') as firstname," +
     " COALESCE(ps.last_name, '') as lastname," +
     " COALESCE(p.program_name, '') as program_Name, " +
     " COALESCE(l.loan_date, '') as loan_date, " +
     " COALESCE(l.return_date, '') as return_date" +
     " FROM devices A" +
     " LEFT JOIN device_loans l on l.device_id = A.device_id" +
     " LEFT JOIN persons ps on ps.person_id = l.person_id" +
     " LEFT JOIN programs p on A.program_id = p.program_id" +
     " WHERE A.device_type = '" + typeName + "'";
     
if(id!=null){
 sql += " and p.program_id = "+ id +";";
 }

BTW: your code has SQL injection risk顺便说一句:您的代码有 SQL 注入风险

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM