使用vb将sql数据库连接到asp.net

时间:2016-09-25 08:07:45

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

我在数据库名称user(用户名,用户ID,国家/地区)中有一个表。我想在asp.net中检索数据。但我在连接SQL数据库时遇到问题。这是我的代码

Public Sub connect()
    Dim DatabaseName As String = "user"
    Dim server As String = "loalhost"
    Dim userName As String = "me"
    Dim password As String = " "
    If Not conn Is Nothing Then conn.Close()
    conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
End Sub

我尝试使用此代码检索数据,但错误

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        conn.Open()
    Catch ex As Exception
    End Try
    Dim cmd As New SqlCommand(String.Format("SELECT username FROM user"))
    cmd.ExecuteNonQuery()
    conn.Close()
End Sub

3 个答案:

答案 0 :(得分:1)

你需要使用ExecuteReader获取所有数据......因为ExecuteNonQuery()用于更新数据库

            SqlCommand cmd1 = new SqlCommand(query1, con);

            SqlDataReader reader = cmd1.ExecuteReader();
            //GridView2.DataSource = reader;
            //GridView2.DataBind();
            while (reader.Read())
            {
               String username =Convert.ToString(reader["username"]);
               // ServicePointDetails t = new ServicePointDetails();
               // t.ServicePointID = Convert.ToString(reader["ServicePointID"]);
               // t.ServicePointName = Convert.ToString(reader["ServicePointName"]);
              //  servicePointDetails_list.Add(t);
            }

了解更多信息ExecuteNonQuery

vb.net

Dim data As SqlDataReader
Dim command As New SqlCommand
command.CommandText = sqlquery
command.Connection = conn
data = cmd.ExecuteReader()
While data.Read
    If data.HasRows = True Then
        Dim userName As String
        userName = data.Item("username")
        //Pupulate a list/do something else 
    End If
End While

答案 1 :(得分:1)

我认为你的表名不正确:数据库是用户,表名是什么?在查询中提供正确的表名

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    Try
        conn.Open()
    Catch ex As Exception
    End Try
    Dim cmd As New SqlCommand(String.Format("SELECT username FROM yourtablename"))
    cmd.ExecuteNonQuery()
    conn.Close()
End Sub

答案 2 :(得分:0)

删除String.Format

Dim cmd As New SqlCommand("SELECT username FROM user")

表名USERS不是USER吗?

为什么使用String.Format作为连接字符串?

Imports System.Data
Imports System.Data.SqlClient
Imports System.Configuration
...
Dim strConnection As String = ConfigurationManager.ConnectionStrings("Something").ConnectionString
Dim con As SqlConnection = New SqlConnection(strConnection)

Dim da As New SqlDataAdapter("SELECT [username] FROM YourTableNameHere", con)
ds = New DataSet
da.Fill(ds, "MyDataTableName")
da.Dispose()

数据集(ds)现在包含用户名列表,如果在函数中,则返回结果:

Return ds