繁体   English   中英

无法使用C#从数据库检索数据

[英]Can't retrieve data from database using c#

我的基础名称为Flashcard,其ID为ID,英语,波兰语。 我想从其中之一中检索名称并将其保存到字符串。 这是我的代码

        public string AskBaseForPolishName(string englishName)
    {
        string polishName;
        SqlConnect.Open();
        SqlCommand cmd = new SqlCommand($"select * from Flashcard where English = {englishName}", SqlConnect);
        SqlParameter param = new SqlParameter();
        SqlDataReader reader = cmd.ExecuteReader();
        while (reader.Read())
        {
            polishName = reader["Polish"].ToString();
        }

        reader.Close();
        SqlConnect.Close();
        return polishName;
    }

并且在“返回”行,Visual Studio发出警告,“使用未分配的变量polishName”。 我无法从基础检索数据。 有什么问题以及如何解决?

这里有三大错误。

首先,SQL语句中的字符串需要用单引号引起来,如下所示:

SqlCommand cmd = new SqlCommand($"select * from Flashcard where English = '{englishName}'", SqlConnect);

似乎可以完全解决您的问题,但情况仍然很糟糕。 想一想,如果您的英文名称本身包含单引号字符,会发生什么情况? 引用将使整个查询摆脱混乱。 更糟糕的是,黑客可以利用该问题在数据库中做非常糟糕的事情。

因此,第二件事就是使用查询参数:

SqlCommand cmd = new SqlCommand("select * from Flashcard where English = @EnglishName", SqlConnect);
cmd.Parameters.Add("@EnglishName", SqlDbType.NVarChar, 20).Value = englishName;

这将保护您免受错误放置或恶意的单引号的影响,并且还请注意,您不再需要担心封装该值。 这样做还有许多其他好处。 查询参数很重要 使用它们。

最后,考虑一下如果查询抛出异常,将会发生什么情况。 执行流将冒出您的方法,并且.Close()命令将永远不会发生。 做到这一点就足够了,有可能使足够多的连接保持打开状态,从而在数据库上造成拒绝服务的情况…… 没有人可以使用它! using块或try/finally块防止出现这种情况。

也有其他一些小事情,但这三件事确实很重要。 像这样将它们放在一起:

public string AskBaseForPolishName(string englishName)
{
    //it's best NOT to re-use the same connection object. Only reuse the same connection string
    using (var cn = new SqlConnection("connection string here"))
    using (var cmd = new SqlCommand("select Polish from Flashcard where English = @EnglishName;", cn))
    {
         cmd.Parameters.Add("@EnglishName", SqlDbType.NVarChar, 20).Value = englishName;
         cn.Open();
         return cmd.ExecuteScalar().ToString();
    }
}

使用此代码段

    static void Read()
{
try
{
    string connectionString =
        "server=.;" +
        "initial catalog=employee;" +
        "user id=sa;" +
        "password=sa123";
    using (SqlConnection conn =
        new SqlConnection(connectionString))
    {
        conn.Open();
        using (SqlCommand cmd =
            new SqlCommand("SELECT * FROM EmployeeDetails", conn))
        {
            SqlDataReader reader = cmd.ExecuteReader();

            if (reader.HasRows)
            {
                while (reader.Read())
                {
                    Console.WriteLine("Id = ", reader["Id"]);
                    Console.WriteLine("Name = ", reader["Name"]);
                    Console.WriteLine("Address = ", reader["Address"]);
                }
            }

            reader.Close();
        }
    }
}
catch (SqlException ex)
{
    //Log exception
    //Display Error message
}
}

暂无
暂无

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

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