2013-07-21 60 views
4

primary_student_table中有10行。獲取VB.NET中SQL Server表中的行數

當我執行下面的代碼時,結果是-1。

Dim count As Int16 
con.Open() 
query = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1 " 

cmd = New SqlCommand(query, con) 

count = cmd.ExecuteNonQuery 
MsgBox(count) 

con.Close() 

上述代碼中的問題是什麼?

+1

** 1。**脫離主題,但仍然是一個潛在的問題:您不在'cmd'上調用'Dispose'和'con'完成使用後。 ** 2。** Int16沒有什麼問題,但在VB.NET中,您通常會使用關鍵字Short來引用該類型。 ** 3。**理想情況下,您可以在最遲的時刻調用'con.Open()',即在執行命令之前;即通常儘量保持連接在儘可能短的時間內打開。 – stakx

+0

除了491243提到的問題外,'count(*)'和'count(row)'可以產生不同的結果。 – jmoreno

回答

4

的解決辦法是更換

count = cmd.ExecuteNonQuery 

count = cmd.ExecuteScalar 

像羅伯特Beaubien在他的評論說

+0

最好的答案 –

11

您應該使用ExecuteScalar()而不是ExecuteNonQuery(),因爲您正在提取值。

count = Convert.ToInt16(cmd.ExecuteScalar()) 
MsgBox(count.ToString()) 

對於正確的編碼

  • 使用using語句正確的對象處理
  • 使用try-catch塊妥善處理異常

示例代碼:

Dim connStr As String = "connection string here" 
Dim query As String = "SELECT COUNT(roll) AS rollcount FROM primary_student_table WHERE admityear = 2011 AND batch = 1" 
Using conn As New SqlConnection(connStr) 
    Using comm As New SqlCommand() 
     With comm 
      .Connection = conn 
      .CommandText = query 
      .CommandType = CommandType.Text 
     End With 
     Try 
      Dim count As Int16 = Convert.ToInt16(cmd.ExecuteScalar()) 
      MsgBox(count.ToString()) 
     Catch(ex As SqlException) 
      ' put your exception here ' 
     End Try 
    End Using 
End Using 
+0

謝謝。沒有冒犯性,是否有其他技術少編碼? –

+0

你爲什麼要那樣? –

+0

我需要它用於我的項目。我只是一個初學者,我不能完全理解這個答案 –

1
MysqlConn = New MySqlConnection 
    MysqlConn.ConnectionString = "server=localhost;userid=root;password=1234;database=dblms" 
    Dim READER As MySqlDataReader 

    Try 
     MysqlConn.Open() 
     Dim Query As String 

     Query = "Select * from dblms.accounts" 
     COMMAND = New MySqlCommand(Query, MysqlConn) 
     READER = COMMAND.ExecuteReader 
     Dim count As Integer 
     count = 0 
     While READER.Read 
      count = count + 1 

     End While 
     MysqlConn.Close() 

    Catch ex As MySqlException 
     MessageBox.Show(ex.Message) 
    Finally 
     MysqlConn.Dispose() 

    End Try 

count中的值將是表中的行數:)希望這有助於