2012-04-08 67 views
2

我想在VB中显示来自SQL服务器的查询结果。我写了下面的代码,但没有得到如何“只显示结果”;如何在VB中显示来自SQL服务器的查询结果?

Public Function ConnectToSQL() As String 
     Dim con As New SqlConnection 
Try 
      con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm" 
      Dim cmd As New SqlCommand("SELECT username FROM users WHERE username='user'", con) 
      con.Open() 
      Console.WriteLine("Connection Opened") 

      ' Execute Query 
      Dim reader As SqlDataReader = cmd.ExecuteReader() 
      While reader.Read() 
       Console.WriteLine(String.Format("{0}, {1}", _ 
        reader(0), reader(1))) 

      End While 
     Catch ex As Exception 
      MessageBox.Show("Error while connecting to SQL Server." & ex.Message) 
     Finally 
      con.Close() 'Whether there is error or not. Close the connection. 
     End Try 
     Return reader 
    End Function 

任何一个可以指导?谢谢

+0

请阅读教程并发布[更少的问题](http://stackoverflow.com/users/1134935/abdulaziz?tab=questions) – Andomar 2012-04-08 10:47:13

+0

http://www.csharp-station.com/Tutorials/AdoDotNet/Lesson04 .aspx清单1 – mola10 2012-04-08 10:51:27

+0

@ mola10谢谢你的回答,你能指导一下VB中的东西吗?谢谢 – AbdulAziz 2012-04-08 11:33:24

回答

4

我纠正了一些东西,现在你的功能对我来说工作得很好:

Public Function ConnectToSQL() As String 
    Dim con As New SqlConnection 
    Dim reader As SqlDataReader 
    Try 
     con.ConnectionString = "Data Source=(local);Initial Catalog=TestDatabase;Persist Security Info=True;User ID=sa;Password=afm" 
     Dim cmd As New SqlCommand("SELECT username, WindowsLogin FROM users WHERE username='user'", con) 
     con.Open() 
     Console.WriteLine("Connection Opened") 

     ' Execute Query ' 
     reader = cmd.ExecuteReader() 
     While reader.Read() 
      Console.WriteLine(String.Format("{0}, {1}", _ 
       reader(0), reader(1))) 
      'NOTE: (^^) You are trying to read 2 columns here, but you only  ' 
      ' SELECT-ed one (username) originally...        ' 
      ' , Also, you can call the columns by name(string), not just by number ' 

     End While 
    Catch ex As Exception 
     MessageBox.Show("Error while connecting to SQL Server." & ex.Message) 
    Finally 
     con.Close() 'Whether there is error or not. Close the connection. ' 
    End Try 
    'Return reader { note: reader is not valid after it is closed }   ' 
    Return "done" 
End Function 

让我知道如果您有任何问题。

+0

非常感谢。它对我和它的工作确实有帮助。我也从你的回答中知道我错在哪里。再一次感谢你。 – AbdulAziz 2012-04-09 09:49:37