[英]Read a value from the database and save it into a variable
我想訪問我的 SQL 服務器數據庫並檢索具有特定 ID 的某些列的值。 我將 id 作為在 dataGridView 表中的數據庫打印,因此用戶選擇的行的第一個單元格是 id。 這是代碼
con3.Open();
if (typeBOX.SelectedIndex == 0)
{
pictureBox1.Image = Organizer.Properties.Resources.b_height_years;
ChartForm.ImageSet = 1;
pictureBox1.Invalidate();
SqlCommand cmd1 = new SqlCommand("select Height,Age from data where Id = '" + dataGridView1.SelectedCells[0].Value.ToString() + "'", con3);
// SqlCommand cmd2 = new SqlCommand("select Age from data where Id = '" + dataGridView1.SelectedCells[0].Value.ToString() + "'", con3);
SqlDataReader reader1 = cmd1.ExecuteReader();
bool flag = false;
while (reader1.Read() && flag == false)
{
string tempHeight = reader1["Height"].ToString();
ChartForm.Height = int.Parse(tempHeight);
string tempAge = reader1["Age"].ToString();
ChartForm.Age = int.Parse(tempAge);
flag = true;
}
}
但是當我嘗試運行代碼時,我得到了錯誤:
System.Data.SqlClient.SqlException:“將 varchar 值“zxxv”轉換為數據類型 int 時轉換失敗。
' FirstName
' 是數據庫中保存的名字,但我在命令cmd1
中沒有。 我只訪問都是整數的height
和age
。 我不知道為什么會這樣。
問題是您將Id
作為字符串而不是 int 傳遞。 因此,錯誤告訴您 SQL 服務器未能將字符串轉換為 int。 發生這種情況的原因是因為Id
包含在單引號中, SQL 將解釋為字符串( varchar/nvarchar
)。
我建議始終參數化您的 SQL 查詢,以避免通過 SQL 注入和類似問題的潛在攻擊。 請參閱為什么我們總是喜歡在 SQL 語句中使用參數? .
您還需要確保從dataGridView
中選擇正確的值,正如@RussW 在他們的回答中提到的那樣。 您正在選擇FirstName
字段,因此也許您可以使用:
int selectedRowIndex = datagridview1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = datagridview1.Rows[selectedRowIndex ];
int id = int.Parse(selectedRow.Cells["Id"].Value.To);
或者
int rowIndex = dataGridView1.CurrentCell.RowIndex;
int columnIndex = dataGridView1.CurrentCell.ColumnIndex;
int id = int.Parse(dataGridView1.Rows[rowIndex].Cells[columnIndex].Value.ToString());
下面是一個可以幫助您入門的示例:
string query = "select Height, Age from data where Id = @id"; // parameter @id in string
SqlCommand cmd1 = new SqlCommand(query, con3); // create command with string
// get the correct row and cell
int selectedRowIndex = dataGridView1.SelectedCells[0].RowIndex;
DataGridViewRow selectedRow = dataGridView1.Rows[selectedRowIndex];
int id = int.Parse(selectedRow.Cells["Id"].Value.ToString()); // parse id to int
// create sql parameter and add to SqlCommand
SqlParameter param1 = new SqlParameter("@id", id);
cmd1.Parameters.Add(param1);
// continue your code...
SqlDataReader reader1 = cmd1.ExecuteReader();
....
請注意,當使用參數化查詢時,無需將參數括在引號中,它會為您處理。 請參閱SqlCommand.Parameters文檔。
我敢打賭,您收到該錯誤是因為您試圖將 Id 從數據中的錯誤單元格中提取出來。 錯誤消息指出嘗試將值“zxxv”轉換為 int 時發生錯誤。 這意味着存儲在以下位置的值:
dataGridView1.SelectedCells[0]
是'zxxv'。 當 SQL 服務器嘗試將該值與 int 列進行比較時,將發生錯誤。 看起來您可能單擊了 dataGridView1 中包含名字的單元格,但 id 位於不同的列中,或者被隱藏。 這只是一個瘋狂的猜測,但如果沒有您的代碼的 rest,這是我能做的最好的事情。 像這樣的東西會修復它嗎?
dataGridView1.SelectedRows[0].Cells[0].Value
或者:
dataGridView1.SelectedRows[0].Cells["Id"].Value
我完全同意其他人說你應該將 id 作為參數傳遞的觀點。 你也應該這樣做。 但我不認為缺少參數是導致錯誤的原因。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.