VB.NET Declaration error - sql

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

Related

Hi folks. I am trying to update an app to VB dot net from vb6 and have enouctered a really basic problem. I will add the code of course in a sec. I

Trying to update an old VB6 app to VB.Net. I am having trouble with syntax, I think. In any case it is a simple matter of inserting a new record to the autolog table. (code below).
I would like to ask something else that is often not documented too. It seems that I have to use command builders and so on - is there no way I can simply use an SQL statement and execute it against the background table? The tables are in Access while I am developing but will be scaled up on the final release of the software.
I have altered my code to the following by making use of the error suggestions at the foot of mygui.
It now looks like this and the only thing is that it is throwing a logic error at me which is that every end function must have a preceding "function". Perhaps I am being a little bit dim
Function MAutolog(ByVal Action As String) As Boolean
Dim SQL = "Insert Into Autolog (Action) Values (#Action)"
Using con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\PC User\Documents\Freightmaster\resources\freightmaster.accdb"),
cmd As New OleDb.OleDbCommand(SQL, con)
cmd.Parameters.Add("#Action", OleDb.OleDbType.VarChar).Value = Action
con.Open()
cmd.ExecuteNonQuery()
End Using
MAutolog = True
End Function
I would like to thank you for your help in advance. I can not tell you how much I will appreciate it.
Code
Module ModFunctions
Function MAutolog(ByVal UserID As Long, ByVal Action As String) As Boolean
Dim dbprovider As String
Dim dbsource As String
Dim mydocumentsfolder As String
Dim fulldatabasepath As String
Dim TheDatabase As String
Dim SQL As String
Dim DS As New DataSet
Dim da As OleDb.OleDbDataAdapter
Dim con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\PC User\Documents\Freightmaster\resources\freightmaster.accdb")
con.Open()
'----------------------------
SQL = "Select * from Autolog"
da = New OleDb.OleDbDataAdapter(SQL, con)
da.Fill(DS, "Log")
con.Close()
Dim CB As New OleDb.OleDbCommandBuilder(da)
Dim DSNEWROW As DataRow
DSNEWROW = DS.Tables("Log").NewRow()
DSNEWROW.Item("UserID") = UserID
DSNEWROW.Item("Action") = Action
DS.Tables("log").Rows.Add(DSNEWROW)
da.Update(DS, "log")
MAutolog = True
End function
Database objects like Connection and Command use unmanaged code and need their Dispose methods to release these resources. Either call this method on these objects or use Using...End Using blocks which will do this for you even if there is an error. In this code, both the Connection and Command are included in the Using block by separating them be a comma.
By Val is the default so is not necessary.
Always use parameters to avoid sql injection. Using values directly from user input can allow malicious code to be executed on your database. The value of a parameter is not considered as executable code by the database.
OleDb does not care about parameter names. You could just as easily use ? in the sql statement. I use names for readability. You do need some sort of name to add the parameter. OleDb considers the position of the parameter in the sql statement. The position must match the order that the parameters are added to the parameters collection.
This is the code for the Insert if UserID in an auto-number field. You do not provide a value for auto-number fields. The database will handle that.
Function MAutolog(Action As String) As Boolean
Dim SQL = "Insert Into Autolog (Action) Values (#Action)"
Using con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\PC User\Documents\Freightmaster\resources\freightmaster.accdb"),
cmd As New OleDbCommand(SQL, con)
cmd.Parameters.Add("#Action", OleDbType.VarChar).Value = Action
con.Open()
cmd.ExecuteNonQuery()
End Using
MAutolog = True
End Function
If UserID is not auto-number
Function MAutolog(UserID As Long, Action As String) As Boolean
Dim SQL = "Insert Into Autolog (UserID, Action) Values (#UserID, #Action)"
Using con As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\PC User\Documents\Freightmaster\resources\freightmaster.accdb"),
cmd As New OleDbCommand(SQL, con)
cmd.Parameters.Add("#UserID", OleDbType.Integer).Value = UserID
cmd.Parameters.Add("#Action", OleDbType.VarChar).Value = Action
con.Open()
cmd.ExecuteNonQuery()
End Using
MAutolog = True
End Function

How can I add the value of a single Cell from Access database to a string variable

As the title says I have a MS Access database from where I need to find a specific dataset determined by a String Value. the reason for having to do this is so I can find the value of a single cell in this datase which has to be used as a path to find a certain file. my approach so far is the following:
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ExaptLokal.accdb")
Dim cmd As New OleDb.OleDbCommand
Dim dt As New DataTable
Dim da As New OleDb.OleDbDataAdapter
Dim sql As String
sql = "SELECT NC_KEY FROM EXAPT_NC_KOPF_DATEN WHERE NC_PROGRAMM_NAME =" & ProgrammNr.Text.ToString
MsgBox(sql)
conn.Open()
cmd.Connection = conn
cmd.CommandText = sql
da.SelectCommand = cmd
da.Fill(dt)
fullpath = dt.ToString
at the end I would like to have the result from my SQL Query as the value of my "fullpath" variable but so far the da.Fill(dt) row is giving me a hard time saying there is a conflict with the datatype.
Is the datatable even needed in this case or might I be able to skip that step and get the result of the query directly in the fullpath variable?
Thanks to everyone in advance
Edit: Thanks for the help (though not the friendliest but who am I to judge) I finally got it to work with the Execute Scalar method. I would just wish newbies to this website would be greeted a little better lol
have a great day
I moved the connection string to a class level variable so you can use it in other methods.
I separated your data access code from your user interface code passing the value from the text box to a function that returns the path.
I changed your select statement to use parameters. Always use parameters to avoid sql injection and avoid errors.
Use Using...End Using blocks to ensure that your database objects are closed and disposed. This Using block covers both the command and the connection.
You can pass the .CommandText and the .Connection directly to the constructor of the command.
When adding parameters to the parameters collection you provide the parameter name, the datatype form the database, and the size of the field. I had to guess at the type and size so, check your database for the actual values.
Since you are expecting a single value you can use .ExecuteScalar.
Private ConStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\ExaptLokal.accdb"
Private Function GetPath(ProgrammNr As String) As String
Dim fullpath As String
Dim sql = "SELECT NC_KEY FROM EXAPT_NC_KOPF_DATEN WHERE NC_PROGRAMM_NAME = #ProgrmmNr"
Using conn As New OleDb.OleDbConnection(ConStr),
cmd As New OleDb.OleDbCommand(sql, conn)
cmd.Parameters.Add("#ProgrmmmNr", OleDbType.VarChar, 100).Value = ProgrammNr
conn.Open()
fullpath = cmd.ExecuteScalar.ToString
End Using
Return fullpath
End Function
Usage...
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim fullpath = GetPath(ProgrammNr.Text)
End Sub

Visual Basic Built in database Connection String Syntax Error

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

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 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.