【问题标题】:Retrieve records from Sqlserver db with VB .net使用 VB .net 从 Sqlserver db 检索记录
【发布时间】:2012-04-27 16:06:47
【问题描述】:

这是我的工作:

Dim connstr = "data source=mydatasource;initial catalog=gcs_dw;persist security   info=True;user id=myuser;password=mypassword;Asynchronous Processing=True"
Dim sqlquery = "SELECT * FROM Customer WHERE CITY = 'Anytown'"
Dim connection As SqlConnection = New SqlConnection(connstr)
connection.Open()

Dim command As SqlCommand = connection.CreateCommand()
command.CommandText = sqlquery
Dim reader As SqlDataReader = command.ExecuteReader()
reader.Read()
Console.WriteLine(reader.ToString)
connection.Close()
Console.Read()

如您所见,我正在尝试将查询结果显示到命令行,目前它显示的只是“System.Data.SqlClient.SqlDataReader”。我的 sql 查询的结果去哪了,为什么我检索不到?

【问题讨论】:

    标签: .net sql-server vb.net ado.net


    【解决方案1】:

    这就是问题所在:

    Console.WriteLine(reader.ToString)
    

    您直接在阅读器上调用ToString,而不是要求它从当前行获取特定值。比如:

    Console.WriteLine(reader.GetString(0))
    

    应该没问题。

    【讨论】:

    • 我知道 .ToString 所做的正是它所假设的,我只是不知道还能使用什么。 .GetString 和 .GetValue 都运行良好。谢谢!
    【解决方案2】:
    Dim str As String
    
    Dim myConn As SqlConnection = New SqlConnection("Server=(local)\netsdk;" & _
                                                    "uid=sa;pwd=;database=master")
    
    str = "CREATE DATABASE MyDatabase ON PRIMARY " & _
          "(NAME = MyDatabase_Data, " & _
          " FILENAME = 'D:\MyFolder\MyDatabaseData.mdf', " & _
          " SIZE = 2MB, " & _
          " MAXSIZE = 10MB, " & _
          " FILEGROWTH = 10%) " & _
          " LOG ON " & _
          "(NAME = MyDatabase_Log, " & _
          " FILENAME = 'D:\MyFolder\MyDatabaseLog.ldf', " & _
          " SIZE = 1MB, " & _
          " MAXSIZE = 5MB, " & _
          " FILEGROWTH = 10%) "
    
    Dim myCommand As SqlCommand = New SqlCommand(str, myConn)
    
    Try
        myConn.Open()
        myCommand.ExecuteNonQuery()
        MessageBox.Show("Database is created successfully", _
                        "MyProgram", MessageBoxButtons.OK, _
                         MessageBoxIcon.Information)
       Catch ex As Exception
           MessageBox.Show(ex.ToString())
       Finally
           If (myConn.State = ConnectionState.Open) Then
               myConn.Close()
           End If
       End Try
    

    结束子

    【讨论】:

      猜你喜欢
      • 2010-10-04
      • 2012-04-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-08-09
      相关资源
      最近更新 更多