Why is SQL not picking up parameter - sql

I'm executing the code below but i am getting an error message saying that one or more required parameters is not provided. The only parameter that I can see is the strMyDomain which is provided. I put the MessageBox statement in temporarily just to confirm that the variable is getting a value. I must not have coded the SQL correctly to pick the value up but I can't see the error.
Dim strMyDomain = Environment.UserDomainName
MessageBox.Show("User domain is: " & strMyDomain)
Dim tblArchTable As New DataTable
Using myConn As New OleDbConnection(strConnectionString)
Dim adpArchives As New OleDbDataAdapter("SELECT ArchID, ArchUserName, ArchUserDomain, ArchDate, ArchRoot, ArchStatus FROM Archives WHERE ArchUserDomain = strMyDomain;", myConn)
adpArchives.Fill(tblArchTable)
DataGV1.DataSource = tblArchTable
End Using

It should be like this :
Dim adpArchives As New OleDbDataAdapter("SELECT ArchID, ArchUserName, ArchUserDomain,
ArchDate, ArchRoot, ArchStatus FROM Archives WHERE ArchUserDomain = '" & strMyDomain & "'", myConn)
But it has sql injection risk, best practice is to use parameterized query like below :
Dim adpArchives As New OleDbDataAdapter("SELECT ArchID, ArchUserName, ArchUserDomain,
ArchDate, ArchRoot, ArchStatus FROM Archives WHERE ArchUserDomain = ?", myConn)
adpArchives.SelectCommand.Parameters.Add(New OleDbParameter("#strMyDomain", strMyDomain))
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used.
For more detail, please read this

Related

Visual Studio Vb.net loaded dataset from oracle query missing or replacing first row of data

I have a vb.net application program that is suppose to query a oracle/labdaq database and load the dataset into a datatable. For some reason the query works fine and there is no exception thrown, however, when I load the data it seems to be missing the first row. I first noticed the issue when I did a query for a single row and it returned zero rows when I checked the datatable's row amount during debugging. I then compared all my data sets to a data miner application straight from the oracle source and i seems to always be missing one, the first, row of data when I use the application.
here is the code... I changed the query string to something else to maintain company privacy
Private Sub CaqOnSQL(strFileDirect As String)
Try
Dim connString As String = ConfigurationManager.ConnectionStrings("CA_Requisition_Attachments.Internal.ConnectionString").ConnectionString
Dim conn As New OracleConnection With {
.ConnectionString = connString
}
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
conn.Open()
Dim Cmd As New OracleCommand(strQuerySQL, conn) With {
.CommandType = CommandType.Text
}
Dim dr As OracleDataReader = Cmd.ExecuteReader()
dr.read()
Dim dt As New DataTable
dt.TableName = "RESULTS"
dt.Load(dr)
ExcelFileCreation(dt, strFileDirect)
You should remove the line:
dr.read()
The call to Read is what is causing you to skip the first row, when combined with the DataTable Load method.
In addition, I have taken the liberty to make some additional changes to your code for the purposes of Good Practice. When using Database objects like Connection and Command, you should wrap them in Using blocks to ensure the resources are released as soon as possible.
Dim dt As New DataTable()
dt.TableName = "RESULTS"
Using conn As New OracleConnection(connString)
conn.Open()
Dim strQuerySQL As String = "SELECT * FROM REQUISITIONS " &
"WHERE DATE BETWEEN TO_DATE('12/10/2020','MM/dd/yyyy') AND " &
"TO_DATE('12/14/2020','MM/dd/yyyy') " &
"ORDER BY ID"
Using command = New OracleCommand(strQuerySQL , conn)
Using dataReader = command.ExecuteReader()
dt.Load(dataReader)
End Using
End Using
End Using
Note: Be wary of Using blocks when using a DataReaderas you may find the connection is closed when you don't want it to be. In this case, the DataReader is used entirely within this function and is safe to use.

Data Mismatch Error in VB.net SQL statement

I have this code:
Protected Sub unlikebtn_Click(sender As Object, e As EventArgs) Handles unlikebtn.Click
Dim strSQL As String
Dim MemberDataConn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & Server.MapPath("database/Database.mdb"))
Dim MemberCommand As New OleDbCommand(strSQL, MemberDataConn)
MemberDataConn.Open()
MemberCommand.Connection = MemberDataConn
MemberCommand.CommandText = "DELETE FROM LIKES WHERE user_id ='" & Session("user_id") & "' AND post_id = '" & Session("post_id") & "'"
MemberCommand.ExecuteNonQuery()
MemberDataConn.Close()
likebtn.Visible = True
unlikebtn.Visible = False
End Sub
When I run it, I get an error on the .ExecuteNonQuery():
System.Data.OleDb.OleDbException: 'Data type mismatch in criteria expression.
I don't think the problem is the data-types in the database...
It is (almost) always a bad idea to concatenate values into an SQL command. Instead, you should use SQL parameters to pass the values.
Also, instances of some classes, such as an OleDbConnection, use unmanaged resources and you have to tell the .NET Framework to dispose of those resources when you've finished using them. You can either call the .Dispose() method yourself or use the Using construct. The latter is tidier as it will take care of the disposal even if there was a problem.
So your code could look like:
Dim strSQL As String = "DELETE FROM LIKES WHERE user_id = ? AND post_id = ?"
Using conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0; data source=" & Server.MapPath("database/Database.mdb"))
Using sqlCmd As New OleDbCommand(strSQL, conn)
'TODO: set the OleDbType to match the columns in the database '
sqlCmd.Parameters.Add(New OleDbParameter With {
.ParameterName = "#UserId",
.OleDbType = OleDbType.VarWChar,
.Size = 32,
.Value = CStr(Session("user_id"))})
sqlCmd.Parameters.Add(New OleDbParameter With {
.ParameterName = "#PostId",
.OleDbType = OleDbType.Integer,
.Value = CInt(Session("post_id"))})
conn.Open()
sqlCmd.ExecuteNonQuery()
conn.Close()
End Using
End Using
likebtn.Visible = True
unlikebtn.Visible = False
The ?s in the SQL command are placeholders for the parameters. The parameter names aren't used, but it makes it easier to see what is what in the code. Because the names aren't used, the parameters must be added in the same order as the corresponding placeholders. You will need to adjust the types of the parameters (and the sizes for strings) to match the column types in the database.
Incidentally, if the site is to run under IIS, then you could put the database in the App_Data directory as nothing in there will be served to a client, by default. Also, SQL Server is a more suitable database for a multi-user environment - you can use the Express edition for free.

Adding SQL Parameter fails

This is a new concept for me and I can't quite see what's causing the error
I'm attempting to populate a datagridview control from a single field in an Access database (from a combo and Text box source).
Using literals works, but not with the parameter.
Dim conn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & Backend & ";Persist Security Info=False;")
Dim command As New OleDbCommand("Select Year from tblTest ", conn)
Dim criteria As New List(Of String)
If Not cboYear.Text = String.Empty Then
criteria.Add("Year = #Year")
command.Parameters.AddWithValue("#Year", cboYear.Text)
End If
If criteria.Count > 0 Then
command.CommandText &= " WHERE " & String.Join(" AND ", criteria)
End If
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
Dim UserRet As New DataTable
UserQuery.Fill(UserRet)
With frmDGV.DataGridView2
.DataSource = UserRet
End With
frmDGV.DataGridView2.Visible = True
frmDGV.Show()
Trying to Fill the datatable shows exception 'No value given for one or more required parameters.'
The value of command.CommandText at that point is "Select Year from tblTest WHERE Year = #Year"
Your instance of OleDbDataAdapter was created using two parameters query text and connection.
Dim UserQuery As New OleDbDataAdapter(command.CommandText, conn)
In this case DataAdapter doesn't know about parameters at all.
Instead use constructor with paremeter of type OleDbCommand.
Dim UserQuery As New OleDbDataAdapter(command)
In your code instance of OleDbCommand already associated with connection

Executing an SQL query in an Access Database in VB.NET

I have already posted one question about this piece of code before lol. But now I am having a different problem and need help with it. Basically this is code for a search button on a Windows Form coded in VB.NET.
Private Sub SearchButton_Click(sender As Object, e As EventArgs) Handles SearchButton.Click
Dim cnnOLEDB As New OleDbConnection
Dim cmdOLEDB As New OleDbCommand
Dim strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & System.Environment.CurrentDirectory & "\All Keyed Up, Lock & Safe, LLC.accdb"
cnnOLEDB.ConnectionString = strConnectionString
cnnOLEDB.Open()
Dim Connection As New SqlClient.SqlConnectionStringBuilder
Connection.DataSource = "file:///C:\Users\thelukester145\Documents\All%20Keyed%20Up\All%20Keyed%20Up,%20Lock%20&%20Safe,%20LLC.accdb"
Dim objSQLConnection = New SqlClient.SqlConnection(Connection.ConnectionString)
Dim cmd As New SqlCommand()
Dim myTable As New DataTable()
Dim SearchFor = SearchBox.Text
If AddressButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [Address] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
ElseIf NumberButton.Checked Then
cmd.Connection = objSQLConnection
cmd.CommandText = "SELECT * FROM [McDonald's-Corporate Stores] WHERE [McOpCo#] LIKE '%" & SearchFor & "%'"
Dim myAdapter As New SqlDataAdapter(cmd)
myAdapter.Fill(myTable)
DataGrid.DataGridView1.DataSource = myTable
End If
DataGrid.Show()
cnnOLEDB.Close()
End Sub
The database that is attempting to be searched is a database of customers for our family buisness. I am trying to search by either the address or store number of our customer. I've worked through who knows how many fatal errors but the newest one has me sort of stumped. It is crashing on myAdapter.Fill(myTable). The error message it gives is this:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: SQL Network Interfaces, error: 25 - Connection string is not valid)
Any help would be much appreciated :)
Well, you are freely mixin OleDb classes with SqlClient classes. The two are for different database types. OleDb is needed for Access, SqlClient classes are used for Sql Server.
So you need to change all the classes SqlCommand, SqlCommandBuilder, SqlDataAdapter,SqlConnectionStringBuilder with the corresponding classes OleDbCommand, OleDbCommandBuilder, OleDbDataAdapter, OleDbConnectionStringBuilder
Infact, the error message is emitted by the SqlClient library that tries to use your connection string as it was a connectionstring for an SQL Server database and, of course, it fails to find it.
Also, I am not sure about that, but probably the DataSource property doesn't need the prefix file:/// and the Encoding of spaces with %20

How to use parameters "#" in an SQL command in VB

I have this code to update my SQL database from data in a textbox, in VB. I need to use parameters in case the text contains a tic mark ,', or a quote ,", etc. Here is what I have:
dbConn = New SqlConnection("server=.\SQLEXPRESS;Integrated Security=SSPI; database=FATP")
dbConn.Open()
MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = '" & TicBoxText.Text & _
"'WHERE Number = 1", dbConn)
MyDataReader = MyCommand.ExecuteReader()
MyDataReader.Close()
dbConn.Close()
And this is my lame attempt to set a parameter from what I have seen on the web, which I don't understand all that well.
dbConn = New SqlConnection("server=.\SQLEXPRESS;Integrated Security=SSPI; database=FATP")
dbConn.Open()
MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = #'" & TicBoxText.Text & _
"'WHERE Number = 1", dbConn)
MyDataReader = MyCommand.ExecuteReader()
MyDataReader.Close()
dbConn.Close()
How do you do this? Cause if there is a ' mark in the textbox when I run the code, it crashes.
You are on the right path to avoiding Bobby Tables, but your understanding of # parameters is incomplete.
Named parameters behave like variables in a programming language: first, you use them in your SQL command, and then you supply their value in your VB.NET or C# program, like this:
MyCommand = New SqlCommand("UPDATE SeansMessage SET Message = #TicBoxText WHERE Number = 1", dbConn)
MyCommand.Parameters.AddWithValue("#TicBoxText", TicBoxText.Text)
Note how the text of your command became self-contained: it no longer depends on the value of the text from the text box, so the users cannot break your SQL by inserting their own command. #TicBoxText became a name of the variable that stands for the value in the text of the command; the call to AddWithValue supplies the value. After that, your ExecuteReader is ready to go.
There are a number of improvements in here:
Using dbConn As New SqlConnection("server=.\SQLEXPRESS;Integrated Security=SSPI; database=FATP"), _
MyCommand As SqlCommand("UPDATE SeansMessage SET Message = #Message WHERE Number = 1", dbConn)
'Make sure to use your exact DbType (ie: VarChar vs NVarChar) and size
MyCommand.Parameters.Add("#Message", SqlDbType.VarChar).Value = TicBoxText.Text
dbConn.Open()
MyCommand.ExecuteNonQuery() ' don't open a data reader: just use ExecuteNonQuery
End Using 'Using block will close the connection for you