简体   繁体   English

如何在C#ASP.NET Core中从MySql中选择没有ID的项目

[英]How to select an item from MySql without id in C# ASP.NET Core

I'm trying to get a user from mysql table with a username instead of id in ASP.Net Core, the default column in GET method is id. 我正在尝试从mysql表中获取一个用户名,而不是ASP.Net Core中的id,GET方法中的默认列是id。 I tried to change it to username, but the column is unknown. 我试图将其更改为用户名,但该列未知。

In my table, username, password and email are in TEXT type, id in INT type. 在我的表格中,用户名,密码和电子邮件为TEXT类型,id为INT类型。

My changed code is: 我更改的代码是:

// GET: api/Person/XXX
[HttpGet("{uname}", Name = "Get")]
public Person Get(string uname)
{
    ConnectMysql();

    Person p = new Person();
    string queryString = "SELECT * FROM users WHERE uname = " + uname;

    MySqlCommand cmd = new MySqlCommand(queryString, conn);

    MySqlDataReader myReader = cmd.ExecuteReader();

    if (myReader.Read())
    {
        p.id = (int)myReader["id"];
        p.name = myReader["uname"].ToString();
        p.password = myReader["pword"].ToString();
        p.email = myReader["email"].ToString();

        return p;
    }
    else
    {
        return null;
    }
}

And then I try to get an item in table with calling http://localhost:54203/api/Person/q ('q' is an item exists in the table). 然后,我尝试通过调用http:// localhost:54203 / api / Person / q (“ q”是表中存在的项)来获取表中的项。

The error is MySql.Data.MySqlException:Unknown column 'q' in 'where clause' 错误是MySql.Data.MySqlException:'where子句'中的未知列'q'

How can I fix it? 我该如何解决?

You need single quotes around values, like this: 您需要在值周围加上单引号,如下所示:

string queryString = "SELECT * FROM users WHERE uname = '" + uname + "'";

Without them, MySql tries to interpret your uname value as a column name. 没有它们,MySql尝试将您的uname值解释为列名。

BUT DON'T DO THAT! 但是不要这样做!

That code is crazy-vulnerable to sql injection attacks. 该代码很容易受到sql注入攻击的攻击。 Do that and your site will hacked before you sign up your first user. 这样做,您的网站将在您注册第一个用户之前被黑。

Structure the code more like this: 结构代码如下:

// GET: api/Person/XXX
[HttpGet("{uname}", Name = "Get")]
public Person Get(string uname)
{
   // Don't manage the conneciton like this.
   // .Net uses connection pooling, where in most cases you really do want
   //   a new connection object for each call to the db
   //  ConnectMysql();

    string queryString = "SELECT * FROM users WHERE uname = @uname";

    using (var conn = new MySqlConnection("connection string here"))
    using (var cmd  = new MySqlCommand(queryString, conn))
    {
        cmd.Parameters.Add("@uname", MySqlDbType.VarChar, 20).Value = uname;
        conn.Open();

        using (var myReader As MySqlDataReader = cmd.ExecuteReader())
        {
            if (myReader.Read())
            {
                return new Person() {
                    id = (int)myReader["id"],
                    name = myReader["uname"].ToString(),
                    password = myReader["pword"].ToString(),
                    email = myReader["email"].ToString()
                };
            }
        }
    }
    return null;
}

And while I'm here, that sure looks like you're storing the password in plain text. 而当我在这里时,那肯定看起来像是您以纯文本形式存储了密码。 In any list of security sins , SQL injection is at the top, and plain-text passwords come soon after. 任何安全隐患列表中 ,SQL注入都居于首位,纯文本密码紧随其后。

Try this in your query: 在查询中尝试以下操作:

string queryString = "SELECT * FROM users WHERE uname = '" + uname + "'";

Your problem is with MySql query not ASP.NET. 您的问题是MySql查询而不是ASP.NET。

Edit: I strongly encourage you to use Entity Framework and LINQ for your projects, check them out. 编辑:我强烈建议您对项目使用Entity Framework和LINQ,将其签出。

If the project isn't that serious or you want to use the old ways instead, you should be parameterize your queries: http://csharp-station.com/Tutorial/AdoDotNet/Lesson06 如果项目不是很认真,或者您想使用旧方法,则应该对查询进行参数化: http : //csharp-station.com/Tutorial/AdoDotNet/Lesson06

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

相关问题 ASP.NET C#如何通过从数据库检索的字符串动态选择按文本列出项目 - ASP.NET C# How to Select List Item by Text dynamically through string retrieved from database 从color ='blue'的表中选择ID时,如何在asp.net(c#)上显示表 - how to show table on asp.net(c#) when select id from table where color='blue' 如何从asp.net C#中将arabic插入mysql - how to insert arabic into mysql from asp.net C# 自动 Select 下拉列表中的一项 asp.net c# - Auto Select one item on Dropdownlist asp.net c# C#asp.net核心在没有构造函数的情况下注入DbContext - C# asp.net core inject DbContext without constructor 动态更改ASP.NET C#中的项目而不回发? - Dynamic change to item in ASP.NET C# without postback? 如何使用 C# 在 ASP.NET 核心 MVC 中将 model 从一个动作传递到另一个动作而不使用 TempData - How to pass model from one action to another without using TempData in ASP.NET Core MVC using C# 如何在 Create 方法上设置 Swagger 忽略 id 属性? C# ASP.NET 内核 Swagger - How to set Swagger ignore id property on Create method? C# ASP.NET Core Swagger 选择语句中的asp.net c#mysql方括号 - asp.net c# mysql square brackets in select statement Asp.Net C#Mysql选择参数查询 - Asp.Net C# Mysql Select Query with Parameters
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM