使用c#从数据库中获取数据

时间:2016-09-03 05:19:30

标签: c# mysql

我想从数据库中获取数据。当我给出文件名时我想要的是pageinfo

   public string GetPageInfo(string filenames)
    {
        SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=;Integrated Security=True");

        con.Open();

        SqlCommand command = new SqlCommand("Select pageinfo from T_Pages where @pagename=filenames", con);

        command.Parameters.AddWithValue("@pagename", "filenames");
        // int result = command.ExecuteNonQuery();
        using (SqlDataReader reader = command.ExecuteReader())
        {
            if (reader.Read())
            {
                Console.WriteLine(String.Format("{0}", reader["pageinfo"]));
            }
        }

        con.Close();

    }

2 个答案:

答案 0 :(得分:2)

  

public string GetPageInfo(string filenames)

你的方法要求在块的末尾返回一个字符串。

根据你方法的流程,它最后要做的就是在Console Window

中写出结果
  

if(reader.Read())               {                    Console.WriteLine(String.Format(“{0}”,reader [“pageinfo”]));               }

你必须做出选择:

  1. public string GetPageInfo(string filenames)更改为public void GetPageInfo(string filenames);或者,

  2. 从数据库中返回所需的任何列。正在改变:

  3.   

    if(reader.Read())               {                   Console.WriteLine(String.Format(“{0}”,reader [“pageinfo”]));               }

      

    return reader [“pageinfo”];

答案 1 :(得分:0)

    int businessEntityID = 1;
string firstName = "Sander";
string middleName = null;
string lastName = "Rossel";
using (SqlConnection connection = new SqlConnection("Data Source=(local);Initial Catalog=AdventureWorks2014;Integrated Security=SSPI"))
using (SqlCommand cmd = new SqlCommand("UPDATE Person.Person SET FirstName = @FirstName, MiddleName = @MiddleName, LastName = @LastName WHERE BusinessEntityID = @BusinessEntityID", connection))
{
    cmd.Parameters.AddWithValue("FirstName", firstName);
    if (middleName == null)
    {
        cmd.Parameters.AddWithValue("MiddleName", DBNull.Value);
    }
    else
    {
        cmd.Parameters.AddWithValue("MiddleName", middleName);
    }
    cmd.Parameters.AddWithValue("LastName", lastName);
    cmd.Parameters.AddWithValue("BusinessEntityID", businessEntityID);
    connection.Open();
    cmd.ExecuteNonQuery();
}

我希望它可以帮到你。