0

I am using the built-in database for my program. When I try to put in the connection string, VB cannot detect the connection string and shows a syntax error on line 7 after the new SqlConnection. I am sure that I copied the complete connection string from the properties page.

I read this post but it seems to be a different question. Below is my code for the connection. Is there any mistake in my code? Thanks for all the help!

    Imports System.Data.SqlClient 
    Public Class Login
    Dim cmd As SqlCommand
    Dim dr As SqlDataReader
    Dim da As SqlDataAdapter
    Dim sql As String
    Dim conn As SqlConnection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf";Integrated Security=True")
Keith Stein
  • 6,235
  • 4
  • 17
  • 36
Sukasa
  • 19
  • 5

1 Answers1

1

That'll obviously show you a syntax error, look at your following line:

"C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf"

Replace the double-quotes to ""<abc>"" to get like "<abc>" on execution because you've already used "<abc>" in New SqlConnection("...").

Rather than:

Dim conn As SqlConnection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename="C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf";Integrated Security=True")

you should have:

Dim conn As SqlConnection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf"";Integrated Security=True")
jmcilhinney
  • 50,448
  • 5
  • 26
  • 46
Rohan Bari
  • 7,482
  • 3
  • 14
  • 34
  • Dim conn As SqlConnection = New SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=""C:\Users\zhenwei\source\repos\Cafeteria Ordering System v1.0\Cafeteria Ordering System v1.0\Database1.mdf"";Integrated Security=True") When I do what you suggest the system just recognise the whole line as text. – Sukasa May 01 '20 at 05:00
  • @Sukasa, the whole line is not recognised as text, but the everything within the parentheses is recognised as a single `String`, which is what should be the case. You can even see it in the syntax parser on this site. In your question, the file path part of your connection string is white, because it is not recognised as part of the `String`. If you double up the double-quotes then the whole lot is the same colour because it is recognised as a single `String` literal. The same happens in VS. I have added an edit to this answer that shows just that. – jmcilhinney May 01 '20 at 05:04