ASP.NET(VB)尝试从web.config设置数据库连接

时间:2017-05-30 17:50:32

标签: asp.net vb.net web web-config

我有一个Web表单项目来更新Microsoft SQL 2012数据库表中的列。当我"硬编码"我的SqlConnection的连接信息一切正常。但是,如果我尝试使用ConfigurationManager.ConnectionStrings路由,我会得到一个关键字' id'不支持。我已将Imports.System.Configuration代码包含到我的项目中。下面是我遇到问题的Sub

 Protected Sub BtnSubmit_Click(sender As Object, e As EventArgs) Handles BtnSubmit.Click
    Dim myConn As SqlConnection
    Dim cmd As SqlCommand
    Dim sqlstring, RqType, RqLast, RqFirst, RqOrg, RqEmail, RqNeedDate, SubFirst, SubLast, RqDetails, RqGenDate, RqOperator As String
    RqType = cbxRequestType.SelectedValue
    RqLast = txtReqLastName.Text
    RqFirst = txtReqFirstname.Text
    RqOrg = txtOrganization.Text
    RqEmail = txtEmail.Text
    RqNeedDate = txtReqDate.Text
    SubFirst = txtSubFirst.Text
    SubLast = txtSubLast.Text
    RqDetails = txtReqDetails.Text
    RqGenDate = txtGenDate.Text
    RqOperator = txtOperator.Text
    If Agree.Checked = False Then
        MsgBox("You must agree to the terms before proceeding")
    Else
        myConn = New SqlConnection(ConfigurationManager.ConnectionStrings("PRRWeb").ConnectionString)
        myConn.Open()
            sqlstring = "INSERT INTO Requests (LastName, FirstName, Organization, DateRequested, DateNeeded, OperatorID, SubjectLastName, SubjectFirstName, Notes, TypeID, Email) VALUES ('" + RqLast + "','" + RqFirst + "', '" + RqOrg + "','" + RqGenDate + "', '" + RqNeedDate + "','" + RqOperator + "','" + SubLast + "','" + SubFirst + "','" + RqDetails + "','" + RqType + "','" + RqEmail + "')"
            cmd = New SqlCommand(sqlstring, myConn)
            cmd.ExecuteNonQuery()
        myConn.Close()
        MsgBox("Your request has been submitted.", MsgBoxStyle.Information)
        Response.Redirect(Request.RawUrl)
    End If

1 个答案:

答案 0 :(得分:0)

通过向我的web.config添加连接字符串解决了这个问题,如此

<connectionStrings >
<add
  name="PRRWeb"
  connectionString="Server=server;Database=DB;Timeout=200;User ID=user; Password=Password; Trusted_Connection=False;"
  providerName="System.Data.SqlClient"/>

然后将其添加到我的vb代码

myConn = New SqlConnection(ConfigurationManager.ConnectionStrings   ("PRRWeb").ConnectionString)