【发布时间】:2020-12-25 21:13:49
【问题描述】:
我有一个项目设置了 3 个单独的表。我使用了 Visual Studio 的内置设计器。
表格包含
- 学生
- 课程
- 每门课程的测试
所有表共享一个学号。
当我将它们“拖放”到表单上时,我可以毫无问题地获取和访问由 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