使用c#无法返回多个SQL行数据

时间:2016-03-28 05:03:46

标签: c# sql sql-server

我有一个数据库,我用它的点,颜色,宽度等存储多行。我知道这些点是存储的,因为我检查了SQL表,它就在那里。但是,当我尝试重新加载这些点时,它只会加载我存储的最后一行。我无法弄清楚为什么会这样。

  private void opendbtestToolStripMenuItem_Click(object sender, EventArgs e)
    {
        try
        {
            using (SqlConnection conn = new SqlConnection("blahblabhblah; "))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM Line", conn))
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        while (reader.Read())
                        {
                            Shape Line = new Line();            // New line
                            Line.readSQL();
                            shapeList.Add(Line);
                            Invalidate();

                        }
                    }
                }
                conn.Close();
            }

        }
        catch(Exception ex)

        {
            MessageBox.Show(ex.Message);
        }
        }

readSQL函数

public override void readSQL()
    {
        try
        {
            using (SqlConnection conn = new SqlConnection("blahblahblah; "))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand("SELECT * FROM Line", conn))
                {
                    using (SqlDataReader reader = cmd.ExecuteReader())
                    {
                        if (reader != null)
                        {
                            while (reader.Read())
                            {

                                // string s = (reader["ID"].ToString());
                                int x1 = Convert.ToInt32(reader["x1"]);
                                int x2 = Convert.ToInt32(reader["x2"]);
                                int y1 = Convert.ToInt32(reader["y1"]);
                                int y2 = Convert.ToInt32(reader["y2"]);
                                Pt1 = new Point(x1, y1);
                                Pt2 = new Point(x2, y2);
                                PenWidth = Convert.ToInt32(reader["Width"]);
                                PenColor = Color.FromArgb(Convert.ToInt32(reader["Color"]));

                            }
                        }
                    }
                }
                conn.Close();
            }
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message);
           // MessageBox.Show(PenColor.ToString());
           // MessageBox.Show(PenWidth.ToString());
        }
    }

我如何写入数据库

public override void writeSQL()
    {
        using (SqlConnection conn = new SqlConnection("blahblahblah "))
        {
            using (SqlCommand comm = new SqlCommand())
            {
                comm.Connection = conn;
                comm.CommandType = CommandType.Text;
                comm.CommandText = "INSERT INTO Line (x1,x2,y1,y2, Width, Color) VALUES (@val1, @val2, @val3, @val4, @val5, @val6)";
                comm.Parameters.AddWithValue("@val1", Pt1.X);
                comm.Parameters.AddWithValue("@val2", Pt2.X);
                comm.Parameters.AddWithValue("@val3", Pt1.Y);
                comm.Parameters.AddWithValue("@val4", Pt2.Y);
                comm.Parameters.AddWithValue("@val5", PenWidth);
                comm.Parameters.AddWithValue("@val6", PenColor.ToArgb());
                try
                {
                    conn.Open();
                    comm.ExecuteNonQuery();
                    MessageBox.Show("Insertion complete");
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "fuuuu");

                }
            }
            conn.Close();
        }

    }

3 个答案:

答案 0 :(得分:0)

我想你应该试试这个。执行查询并将所有数据加载到datatable。之后,您可以遍历每条记录

string query = "SELECT * FROM Line";
using (SqlCommand cmd = new SqlCommand(query, conn))
{
    DataTable dt = new DataTable();
    dt.Load(cmd.ExecuteReader());  
    foreach (DataRow row in dt.Rows) 
    {
       //manipulate your data
    }   
}

答案 1 :(得分:0)

将sqlDataReader发送到另一个函数并操纵该函数中的数据,如下所示:

    public bool InitializeVariables(SqlDataReader sdr, bool isSingle = true)
    {
        try
        {
            if (sdr.HasRows)
            {
                if (isSingle)
                    sdr.Read();

                //initialize and manipulate data here.

                return true;
            }
            else
                return false;
        }
        catch (System.Exception ex)
        {
            throw ex;
        }
    }

答案 2 :(得分:0)

根据您的代码,Line是一个单一的对象。你在一个Line对象上调用ReadSQL作为一个非静态方法,并期望它返回多行,但这没有用 - 你的方法是在当前对象上设置两个属性,所以根据定义,只会“返回”您收藏中的最后一项。

ReadSQL中的代码在选择特定ID时更有意义,例如

using (var cmd = new SqlCommand("SELECT * FROM Line Where id = @id", conn))
{
  cmd.Parameters.Add(new SqlParameter("Id", SqlDbType.Int) { Value = id });
  //....
}

如果要返回一组行,则需要一个返回行对象集合的方法(在Line对象上或其他地方为静态)。

public static IEnumerable<Line> GetLines(int id)
{
    var returnData = new List<Line>();
    try
    {
        using (var conn = new SqlConnection("blahblahblah; "))
        using (var cmd = new SqlCommand("SELECT * FROM Line", conn))
        {
            conn.Open();

            using (var reader = cmd.ExecuteReader())
            {
                while (reader.Read())
                {
                    // string s = (reader["ID"].ToString());
                    int x1 = Convert.ToInt32(reader["x1"]);
                    int x2 = Convert.ToInt32(reader["x2"]);
                    int y1 = Convert.ToInt32(reader["y1"]);
                    int y2 = Convert.ToInt32(reader["y2"]);

                    returnData.Add(new Line()
                    {
                        Pt1 = new Point(x1, y1),
                        Pt2 = new Point(x2, y2),
                        PenWidth = Convert.ToInt32(reader["Width"]),
                        PenColor = Color.FromArgb(Convert.ToInt32(reader["Color"]))
                    });
                }
            }
            conn.Close();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.Message);
    }


    return returnData;
}