2010-08-16 108 views
0

我在Microsoft SQL Server 2005數據庫中有一個名爲t_Student的表。在該表中有三列,分別爲student_regiNostudent_Namestudent_Email從MS SQL Server 2005中選擇數據

我正在使用以下代碼段來檢索「student_Name」。但不是顯示「student_Name」,而是顯示「System.Data.SqlClient.SqlDataReader」。有什麼問題?

private void GetDatabaseConnection() 
{ 
    string connectionString = @"server=RZS-F839AD139AA\SQLEXPRESS; Integrated Security = SSPI; database = StudentCourseInformation"; 
    connection = new SqlConnection(connectionString); 
    connection.Open(); 
} 

public string GateStudentName(string selectedStudentRegiNo) 
{ 
    GetDatabaseConnection(); 

    string selectedStudentQuery = @"SELECT student_Name FROM t_Student WHERE (
            student_regiNo = 
            '" +selectedStudentRegiNo+ @"' 
            )"; 
    SqlCommand command = new SqlCommand(selectedStudentQuery, connection); 
    SqlDataReader reader = command.ExecuteReader(); 

    string selectedStudentName = Convert.ToString(reader); 
    return selectedStudentName; 
} 

回答

4

使用

return (string)command.ExecuteScalar(); 

至於你必須「在該查詢返回的結果集的第一行的第一列」返回(從MSDN

還可以使用參數化查詢:

var command = new connection.CreateCommand() 
command.CommandText = "SELECT student_Name FROM t_Student WHERE student_regiNo = @number"; 
command.Parameters.AddWithValue(@number, selectedStudentRegiNo); 
+0

感謝abatishchev爲您寶貴的建議。 – Towhid 2010-08-16 08:01:35

+2

@towhidulbashar:不客氣:)不要忘記接受正確的答案。在這裏,在你的其他隊列 – abatishchev 2010-08-16 08:07:36

3

ExecuteReader返回SqlDataReader。您需要使用SqlDataReader API來從中讀取數據。不要忘記查詢可以返回多行,每行有多列。例如:

while (reader.Read()) 
{ 
    string name = reader.GetString(0); 
    Console.WriteLine("Read name: {0}", name); 
} 

,你應該使用參數化查詢,而不是直接包括標識加入SQL進一步說明 - 否則你會把自己暴露給SQL注入攻擊。有關更多信息,請參閱SqlCommand.Parameters的文檔。

最後,您應該爲SqlConnectionSqlCommandSqlDataReader使用using語句,以便您適當處置它們。否則,你將泄漏數據庫連接。

+0

謝謝Jon Skeet。我的問題解決了。 我可以再打擾你嗎?我的代碼有什麼問題,爲什麼它現在在工作? – Towhid 2010-08-16 07:36:47

+1

在你的代碼中,你沒有執行Jon在他的答案中提供的Read()方法。 – 2010-08-16 07:43:58

+0

感謝Ardman的快速反饋。 – Towhid 2010-08-16 07:46:56

1
if (reader.Read()) 
{ 
    string selectedStudentName = reader.GetString(0); 
} 
+0

感謝Pavel Morshenyuk爲您的有效答案。 – Towhid 2010-08-16 08:00:43

0
SqlCommand command = new SqlCommand(selectedStudentQuery, connection); 
SqlDataReader reader = command.ExecuteReader(); 

if(reader.Read()) 
{ 
    return reader["student_Name"]; 
} 
return "not exist"; 
+1

會更好用一個簡短的句子:什麼是最初的代碼爲例,真的發生了什麼這是做這個... – JYL 2012-09-26 13:09:25

+0

感謝第一個代碼是整個閱讀器陣列轉換爲一個字符串,你應該通過索引或其他e,g reader [「student_Name」]和reader [0]在索引零處返回相同的結果來獲得數組中的「student_Name」值 – 2012-09-26 13:55:16

相關問題