2012-04-27 32 views
0

這裏是我的工作:獲取與VB .NET從sqlserver的數據庫記錄

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查詢的結果在哪裏,爲什麼我不能檢索它們?

回答

5

這就是問題所在:

Console.WriteLine(reader.ToString) 

你直接對讀者致電ToString,而不是要求它從當前行的特定值。例如:

Console.WriteLine(reader.GetString(0)) 

應該沒問題。

+0

我知道的ToString在做什麼它是假設的話,我根本不知道該用什麼。 .GetString和.GetValue都很完美。謝謝! – Brian 2012-04-27 16:25:13

0
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 

末次

相關問題