Can';使用Visual Studio在VB.NET中通过连接字符串手动访问本地SQL数据库
我有一个项目设置了3个单独的表。我使用了VisualStudio中的内置设计器 这些表格包含Can';使用Visual Studio在VB.NET中通过连接字符串手动访问本地SQL数据库,sql,vb.net,connection-string,Sql,Vb.net,Connection String,我有一个项目设置了3个单独的表。我使用了VisualStudio中的内置设计器 这些表格包含 学生 课程 每门课程的考试 所有的桌子共用一个studentnumber 当我在表单上“拖放”时,我可以获取和访问VisualStudio自动生成的不同TableAdapter和相应BindingSource的数据。我还可以使用查询生成器从每个表中获取所需的数据 我的问题发生在我试图通过连接字符串手动访问数据库时 我得到这个错误: 无法将文件local path\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数据库设置了一个类似的项目。我在VisualStudio中除了用相同的表创建数据库外,什么也没做
在这里,我可以通过手动连接字符串连接到数据库
我的问题是:为什么我不能在第一个项目中使用连接字符串访问本地数据库?您还没有发布其他连接字符串,但问题可能在于
AttachDbFilename
。DB将已连接,此选项仅用于单用户模式(仅一个连接)。
最好的办法是将数据库永久连接到LocalDB实例(如果您一直在使用该实例)。第二个连接字符串与第一个连接字符串完全相同,但具有不同的filenam。刚刚创建了一个复制品。谢谢你向我澄清这一点。我想可能是这样的。