ASP.Netのお勉強

SQLServerに接続@ASP.Net

SQLServerに接続します。
以下では、SQLServerに接続して、SQL文を発行します。
結果を取得して表示します。

●aspx

<%@ Page Language="VB" AutoEventWireup="false" CodeFile="Default.aspx.vb" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    <title>SQLServerに接続</title>
</head>
<body>
    <form id="form1" runat="server">
        <asp:Button ID="Button1" runat="server" Text="Button" />&nbsp;<br />
        <asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
    </form>
</body>
</html>


●vb

Imports System.Data.SqlClient
Imports System.Data

Partial Class _Default
    Inherits System.Web.UI.Page

    Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click

        Dim dbcon As SqlConnection
        Dim dbcmd As SqlCommand
        Dim dataread As SqlDataReader

        Dim conStr As String
        Dim sqlStr As String
        Dim outStr As String

        conStr = "data source=(local)\SQLEXPRESS;initial catalog=DBNAME;user id=ID;password=PASS;persist security info=True;packet size=4096"

        'SqlConnection作成
        dbcon = New SqlConnection(conStr)

        'DBオープン
        dbcon.Open()

        'SQL文
        sqlStr = "SELECT * FROM TABLE"

        'SQLコマンド作成
        dbcmd = New SqlCommand(sqlStr, dbcon)

        'SQL文実行
        dataRead = dbcmd.ExecuteReader()

        outStr = ""
        '結果を取り出す
        While (dataread.Read())
            outStr += dataread("ID")
            outStr += dataread("NAME")
        End While

        'Labelに結果を表示
        Me.Label1.Text = outStr

        'クローズ処理
        dataRead.Close()
        dbcmd.Dispose()
        dbcon.Close()
        dbcon.Dispose()
    End Sub
End Class


Copyright (C) ASP.Netのお勉強. All Rights Reserved.