简体   繁体   中英

Can't return more than one SQL row data using c#

I have a database where I store multiple lines with its points, color, width, etc. I know that the points are being stored because I checked the SQL table and it is in there. However, when I try to reload these points it will only load the very last line that I stored. I cannot figure out why this is.

  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);
        }
        }

the readSQL function

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());
        }
    }

how I write to the database

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();
        }

    }

I think you should try this. Execute your query and load all your data into datatable . After that you can loop through each record

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
    }   
}

send sqlDataReader to another function and manipulate data in that function, something like that:

    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;
        }
    }

Based on your code, a Line is a singular object. You are calling ReadSQL as a non-static method on a Line object, and expecting it to return more than one line, but this doesn't really make sense - your method is setting two properties on the current object, so by definition, only the last item in your collection will be "returned".

Your code in ReadSQL makes more sense if it was selecting for a specific Id, eg

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

If you want to return a collection of lines, you need to have a method (either as static on the Line object, or elsewhere) that returns a collection of line objects.

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;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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