【问题标题】:Can't access Local SQL database manually by connection string in VB.NET using Visual Studio无法使用 Visual Studio 通过 VB.NET 中的连接字符串手动访问本地 SQL 数据库
【发布时间】:2020-12-25 21:13:49
【问题描述】:

我有一个项目设置了 3 个单独的表。我使用了 Visual Studio 的内置设计器。

表格包含

  1. 学生
  2. 课程
  3. 每门课程的测试

所有表共享一个学号。

当我将它们“拖放”到表单上时,我可以毫无问题地获取和访问由 Visual Studio 自动生成的真正不同的表适配器和相应的绑定源。我还可以使用查询生成器从每个表中获取我需要的数据。

当我尝试通过连接字符串手动访问数据库时出现问题。

我收到此错误:

无法将文件本地路径\HovedDatabase.mdf 作为数据库结果附加,因为该文件已用于数据库本地路径\HovedDatabase.mdf

这是我的代码:

Private Sub FormPrøver3_Load(sender As Object, e As EventArgs) Handles MyBase.Load
    'TODO:   This line of code loads data into the 'StudentDataSet.StudentTabell' table. You can move, or remove it, as needed.
    Me.StudentTabellTableAdapter.Fill(Me.StudentDataSet.StudentTabell)
    Me.StudentTabellTableAdapter.Connection.Close()

    Get_Data_Manualy_Fag()

End Sub

Private Sub Get_Data_Manualy_Fag()
    Try
        'Create variabals for inputcontainer
         Dim Studnr As String = Me.StudentnrLabel1.Text

        'Create a connection to the DataBase
        Dim myConn As SqlConnection
        myConn = New SqlConnection("Initial Catalog=OutComes;Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\HovedDatabase.mdf;Integrated Security=True")

        'Create a Command object.
        Dim myCmd As SqlCommand
        myCmd = myConn.CreateCommand
        myCmd.CommandText = "SELECT Fag FROM Fag3Tabell WHERE Fag = @Studnr"
        myCmd.Parameters.AddWithValue("@Studnr", Studnr)

        'Open the connection.
        myConn.Open()

        'Process the answer
        Dim myreader As SqlDataReader
        myreader = myCmd.ExecuteReader

        'Traverse the DataSet and Display :
        Dim i As Integer = 0
        Do While myreader.Read()
            Me.ComboBox1.Items.Add(myreader.GetString(i))
            i = i + 1
        Loop

        'Close the connection
        myConn.Close()

        'Handle errors
    Catch ex As Exception
        MessageBox.Show(ex.Message)
    End Try

我用类似的 LocalSQL 数据库建立了一个类似的项目。除了使用相同的表创建数据库之外,我在 Visual Studio 中什么也没做。

这里我通过手动连接字符串连接数据库没有问题。

我的问题是:为什么我不能在第一个项目中使用连接字符串访问本地数据库?

【问题讨论】:

    标签: sql vb.net connection-string


    【解决方案1】:

    您尚未发布其他连接字符串,但看起来AttachDbFilename 可能是问题所在。数据库将已附加,此选项仅用于单用户模式(仅一个连接)。 最好的办法是将数据库永久附加到 LocalDB 实例,如果这是您一直使用的。

    【讨论】:

    • 第二个连接字符串与第一个连接字符串完全相同,但文件名不同。刚刚创建了一个副本。感谢您向我澄清这一点。我想可能是这样的。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-24
    相关资源
    最近更新 更多