Visual Basic Built in database Connection String Syntax Error - vb.net

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")

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")

Related

Two Connections types in one method (SQL and OLEDB)

I have two connections types to be used in my app. One is SQL Server, using the SqlClient.Connection type. The other one uses the OleDb.Connection type.
The question is, when using a DataAdapter, DataReader, and Command, how can I use one reference for each with both connections?
As an example, I want to use a reader like this:
Dim MyReader As OleDb.OleDbDataReader
to check my data with an OleDbConnection, and then use same reader to check data from the second SqlClient connection. That is, I want to do something like this (pseudocode):
Dim con
Dim MyReader
con = oledb.connection
MyReader = mymethod(con)
con = sql.sqlclient.conection
MyReader = mymethod2(con)
How can I do this in real code?
I need help in how to declare data components for two different connection types inside the same method or function.
You should declare multiple variables. It's really not a big deal to do so.
But, if you really want to do this (again: not the best idea) one thing you can keep in mind is these objects all inherit from a common set of types in the System.Data.Common namespace. So it possible to write code like this:
Dim con As System.Data.Common.DbConnection = New OleDbConnection("connection string here")
Dim cmd As System.Data.Common.DbCommand = New OleDbCommand("SELECT * ... ", con)
con.Open()
Dim rdr As System.Data.Common.DbDataReader = con.ExecuteReader()
While rdr.Read()
' ...
End While
con.Close()
con = New SqlClient.SqlConnection("connection string here")
cmd = New SqlClient.SqlCommand("SELECT * ...", con)
con.Open()
rdr = cmd.ExecuteReader()
While rdr.Read()
' ...
End While
But again: you really are better off using separate variables.

Getting Data From SQL and into a variable

NET and using MS Access as database. I'm trying to get data from SQL and place it in a variable and print it in a Message box to confirm that the variable holds the data. But when I run my code it gives me an error message and highlights
Dim conn As New OleDbConnection and conn.Open()
"An unhandled exception of type 'System.InvalidOperationException' occurred in System.Data.dll
Additional information: The ConnectionString property has not been initialized."
It does not run the sql query. Please help me figure this out. Merci.
Imports System.Data.OleDb
Public Class ModifyForm
Dim connstring As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source= c:\Databse\Company_db.accdb"
Dim conn As New OleDbConnection
Private Sub eNumText_SelectedIndexChanged(sender As Object, e As EventArgs) Handles eNumText.SelectedIndexChanged
Dim empNum As String
Dim empFname As String
Dim empLname As String
Dim empDept As String
Dim empStat As String
Dim empYears As String
empNum = eNumText.Text
empFname = empFnameText.Text
empLname = empLnameText.Text
empDept = DeptText.Text
empStat = StatText.Text
empYears = yearstext.Text
Dim conn As New OleDbConnection(connstring)
conn.Open()
Dim DBID As String ' Or whatever type you're using for the ID field
Dim DBFirstName As String
Dim SqlQuerry As String = "SELECT * FROM tbl_empinfo WHERE EmpID like empNum"
Dim SqlCommand As New OleDbCommand
Dim SqlAdapter As New OleDbDataAdapter
Dim Table As New DataTable
With SqlCommand
.CommandText = SqlQuerry
.Connection = conn
End With
With SqlAdapter
.SelectCommand = SqlCommand
.Fill(Table)
End With
For i = 0 To Table.Rows.Count - 1
DBID = Table.Rows(i)("EmpID")
DBFirstName = Table.Rows(i)("FirstName")
MsgBox(DBID)
MsgBox(DBFirstName)
Next
conn.Close()
End Sub
End Class
You need to actually use your connection string.
But first let's remove the duplicate declaration of your connection. Remove Dim conn As New OleDbConnection from the very top of your code (the one outside of the method) it's not needed since you are declaring again inside of the method. Then, inside the method update your connection initialization to:
Dim conn As New OleDbConnection(connstring)
More than that, you need to initialize your command, passing it the connection string and query string. The Adapter needs to have a reference to the command and you need to call
SQLAdapter.fill(Table)
To get your data in the table.
Please look up how to use these objects... Simply creating new instances of them doesn't implicitly assign all of the configuration information that each object needs.
One note is to make sure that you dispose your objects that implement the IDisposable interface to free the unmanaged resources. It is not enough to simply close your connection--this will lead to memory leaks, not just with SQL objects but anything that uses resources not directly managed by. .NET
SQLCommand.dispose()
SQLAdapter.dispose()
Table.dispose()
conn.dispose()
conn.close()
And finally, once you get it working using the information provided above and some googling, you then need to address SQLInjection. Right now your query string is prone to injection whereas a user could potentially type some malicious text into the text box you refer to in your query string and manipulate your database without your permission. To get around this, look into parameterized commands.
I'm posting from my phone or else I'd provide a full working set of code; but at the same time I don't want to rewrite the whole thing for you. There should be enough info in this answer to help you do a little research.
This MSDN page contains info on the OleDb data adapter as well as a short example at the end. It also includes links and references for the rest of the OleDb classes and to some tutorials:
http://msdn.microsoft.com/en-us/library/system.data.oledb.oledbdataadapter.aspx
This MSDN page contains info on the SQLDataAdapter and includes a short example at the very bottom. Although a different class, the usage is fundamentally the same as the OleDb classes: http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx
Though not in vb (its in c#) the usage is the same, just slightly different syntax (best I could find from my phone at the moment). Again this is for the SQLDataAdapter class, but usage is fundamentally the same: http://www.codeproject.com/Tips/462730/Five-different-overloads-of-the-DataAdapter-Fill-m

VB.NET Declaration error

I am having some trouble in some Visual Basic code where although I have declared a variable, when I try to give it a value, Visual Studio returns an error saying that the variable hasn't been declared. Here is the block of code:
Private Sub chkbox_ta_CheckedChanged(sender As Object, e As EventArgs) Handles chkbox_ta.CheckedChanged
Dim query As String = "SELECT * FROM [Hiragana List] WHERE Pronunciation='Ta';"
Dim instruction As SqlCommand (query, connection)
Dim da As New SqlDataAdapter
da.SelectCommand = instruction
da.Fill(HiraganaList)
End Sub
The error is thrown up by the 'instruction' variable and Visual Studio hasn't provided any solutions. In addition to this, the query argument within the instruction variable returns the error 'Array bounds cannot appear in type specifiers'. I am still getting used to working with SQL in VB and any explanation which would teach me how to avoid these errors would be very helpful.
Wrong syntax in declaration and initialization of the SqlCommand.
The right syntax is one of the following:
Dim instruction As SqlCommand = new SqlCommand(query, connection)
or
Dim instruction As New SqlCommand (query, connection)
or just
Dim instruction = new SqlCommand(query, connection)
The Dim Statement has numerous variations the should be studied carefully (especially in the early days with the language)
Data types (string, integer, date) do not need a "new" declaration.
But when you define something that is a class (Like SqlCommand or one you create yourself) it will need to be initialized with "new".
Syntax examples from Steve's earlier post
Dim instruction As SqlCommand = new SqlCommand(query, connection)
Dim instruction As New SqlCommand (query, connection)
Dim instruction = new SqlCommand(query, connection)
Some links that might help out:
http://msdn.microsoft.com/en-us/library/47zceaw7.aspx
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand%28v=vs.110%29.aspx

VB.NET - Multiple SQLDataReader's

I develop a lot in ASP.NET and I know that you can only open one SQLDataReader for each SQLConnection. However, this does not appear to be the case in VB.NET (form application) i.e. I have opened multiple SQLDataReaders for one connection object. Is this allowed in VB.NET?
If there is not an obvious answer to this then I will post some code.
Here is some code:
Public Function CheckActiveReviews()
Dim objCon As SqlConnection
Dim objCommand As SqlCommand, objCommand2 As SqlCommand
Dim objDR As SqlDataReader, objDR2 As SqlDataReader
Try
objCon = New SqlConnection("Data Source=TestDatabase;Initial Catalog=TestTable;User ID=TestUser;Password=TestPassword;MultipleActiveResultSets=True")
objCommand = New SqlCommand
objCommand.Connection = objCon
objCommand2 = New SqlCommand
objCommand2.Connection = objCon
objCon.Open()
objCommand.CommandText = "SELECT ID FROM Person WHERE PersonID > 1000"
objDR = objCommand.ExecuteReader()
Do While objDR.Read
objCommand2.CommandText = "SELECT * FROM Sport WHERE PersonID = #PersonID "
objCommand2.Parameters.AddWithValue("#PersonID", objDR("ID"))
objDR2 = objCommand2.ExecuteReader
Loop
Catch ex As Exception
End Try
End Function
You can use multiple data readers if you use MARS - Multiple Active Result Sets - but I wouldn't advise that unless you really need it.
Instead, I'd suggest creating a new SqlConnection object each time you need it - use it for as short a period as you can, then dispose of it (use a Using statement to do this for you). The connection pool will take care of the efficiency in terms of reusing "physical" network connections where possible. That way you don't need to worry about whether the SqlConnection is already open etc - you just always follow the same "create, open, use, dispose" pattern every time.

vb error: Value of type 'String' cannot be converted to 'System.Data.SqlClient.SqlCommand'

I'm a novice VB programmer and I'm sure this solution is trivial, however, I am getting the above error when I try to display the results of one of my Stored Procs in SQL Server which doesn't need any parameters. How can I fix this?
My code excerpt:
Dim SQLCmd as SQLCommand = new SQLCommand()
SQLCmd.CommandText = "Exec AllTableCount"
SQLCmd.CommandType = CommandType.StoredProcedure
SQLCmd.Connection = GlobalFunctions.GlobalF.GetDevSQLServerStoredProcedure(SQLCmd.CommandType)
SQLCmd.ExecuteNonQuery()
MsgBox(SQLCmd.ExecuteNonQuery)
Where GetDevSQLServerStoredProcedure is defined in a different file as:
Public Shared Function GetDevSQLServerStoredProcedure(ByVal SQL As String)
Dim DBConn As SQLConnection
Dim DBCommand As SQLDataAdapter
Dim DSPageData As New System.Data.DataSet
DBConn = New SQLConnection(ConfigurationSettings.AppSettings("AMDMetricsDevConnectionString"))
DBCommand = New SQLDataAdapter(SQL) 'This is the line it errors on'
DBCommand.Fill(DSPageData, "Exceptions")
Return DSPageData
End Function
I can see this SP from VS 2008 in the Server Explorer. So the problem seems to be that I don't know how to connect a data adapter to an SP. Just a string query.
Command text should just be the name of the stored procedure as Tim mentioned.
It looks like the problem you are having now is that you are passinging the CommandType to your method GetDevSQLServerStoredProcedure instead of a string.