如何在C#中从数据库中检索数据?

时间:2014-11-17 12:18:02

标签: c# mysql

我编写了一个控制台基础应用程序,它在数据库中注册一个捐赠者,并且还能够通过搜索名称从数据库中检索数据。我能够正确添加数据但是当我尝试检索数据时出现问题没有出现。这是我的代码:

class bbManager
{
    public string ConnectionString = @"server=localhost;Database=introsw;Uid=root;Pwd=123456";

    public void Registration(BloodBank donor)
    {
        string query = "Insert Into bloodbank(id, name) Values('"+ donor.id +"','"+ donor.name +"')";

        MySqlConnection conn = new MySqlConnection();
        conn.ConnectionString = ConnectionString;
        conn.Open();

        MySqlCommand cmd = new MySqlCommand();
        cmd.CommandText = query;
        cmd.Connection = conn;

        int result = cmd.ExecuteNonQuery();
        if (result == '1')
        {
            Console.WriteLine("Registration Successful...");
        }
    }
    public void SearchByname(string name)
    {
        string query = "select * from bloodbank Where name = '"+ name +"'";
        try
        {
            MySqlConnection conn = new MySqlConnection();
            conn.ConnectionString = ConnectionString;
            conn.Open();

            MySqlDataReader rdr = null;

            MySqlCommand cmd = new MySqlCommand();
            cmd.CommandText = query;
            cmd.Connection = conn;

            rdr = cmd.ExecuteReader();

            while(rdr.Read())
            {
                Console.WriteLine("ID: ", rdr["id"].ToString());
                Console.WriteLine("Name: ", rdr["name"].ToString());
            }
            conn.Close();
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
    }
}

1 个答案:

答案 0 :(得分:3)

最初的问题是

Console.WriteLine("ID: ", rdr["id"].ToString()); 

可能是:

Console.WriteLine("ID: {0}", rdr["id"].ToString());    // http://msdn.microsoft.com/pt-br/library/fc0cx9a5(v=vs.110).aspx

Console.WriteLine("ID: " + rdr["id"].ToString());

TODO:验证SQL参数。 C# SQL parameters

public void Registration(BloodBank donor)
{
    string query = "INSERT INTO bloodbank(id, name) VALUES ('" + donor.id.Replace("'","''") + "','" + donor.name.Replace("'","''") + "');";

    using (MySqlConnection conn = new MySqlConnection())
    {
        conn.ConnectionString = ConnectionString;
        conn.Open();

        try
        {
            RunSQL(query, conn);
            Console.WriteLine("Registration Successful...");
        }
        catch
        {
            Console.WriteLine("Registration Failed...");
        }
    }
}

public void SearchByname(string name)
{
    string query = "SELECT * FROM bloodbank WHERE name = '" + name + "'";
    try
    {
        DataTable DT_Results;
        using (MySqlConnection conn = new MySqlConnection())
        {
            conn.ConnectionString = ConnectionString;
            conn.Open();
            DT_Results = RunSQL(query, conn);
        }

        foreach (DataRow dr in DT_Results.Rows)
        {
            Console.WriteLine("ID: " + dr.Field<string>("id"));
            Console.WriteLine("Name: " + dr.Field<string>("name"));
        }

    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }
}

static public DataTable RunSQL(string sSQL, MySqlConnection MyConnection)
{
    DataTable DT = new DataTable();

    using (MySqlDataAdapter MyDataAdapter = new MySqlDataAdapter(sSQL, MyConnection))
    {
        try
        {
            #region Executa / Preenche o DT
            DT.TableName = "TABELA";
            MyDataAdapter.Fill(DT);
            #endregion
        }
        catch (Exception ex)
        {
            // by Tony - 26-set-2006 
            // Retorna o SQL e o erro, para facilitar o debug do sistema.
            var newexeption = new Exception(sSQL + " " + ex.Message);
            throw newexeption;
        }
    }

    return DT;
}