簡體   English   中英

無法使用C#返回多個SQL行數據

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

我有一個數據庫,我在其中存儲了多行及其點,顏色,寬度等。我知道這些點已存儲,因為我檢查了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();
        }

    }

我認為您應該嘗試一下。 執行查詢並將所有數據加載到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
    }   
}

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

根據您的代碼, Line是單個對象。 您正在將ReadSQL作為Line對象上的非靜態方法進行調用,並期望它返回多行,但這實際上沒有意義-您的方法是在當前對象上設置兩個屬性,因此根據定義,您收藏中的最后一個商品將被“退回”。

如果您選擇特定的ID,則在ReadSQL代碼更有意義,例如

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM