SQL query is not running IN VB.NET - sql

I am fresher in VB.NET and I am trying to execute an SQL query in VB.NET but not showing any value at output. Can u please help me to find where am I going Wrong.
Dim sConnectionString As String _
= "User ID=XXX ;Password=XXX;Initial Catalog=gemXXX;Data Source=SCRBAMSDKBXXXXXX"
Dim objConn As New SqlConnection(sConnectionString)
objConn.Open()
Dim sw ,readerObj
Dim sSQL As String = "select top 1 " & sw & " = e.import from tblrelcoms r , [beant].[dbo].tblequipments e where r.IDEquipment = e.IDEquipment"
Using readerObj As SqlClient.SqlDataReader = cmdObj.ExecuteReader
Dim objCmd As New SqlCommand(sSQL, objConn)
objCmd.ExecuteNonQuery()
TextBox1.Text = sw.ToString()

The problem you have is that you cannot just concatenate a variable into SQL and expect it to be updated once the SQL is executed.
ExecuteScalar is probably the easiest way of achieving what you want:
Dim sConnectionString As String _
= "User ID=XXX ;Password=XXX;Initial Catalog=gemXXX;Data Source=SCRBAMSDKBXXXXXX"
Dim sSQL as string = "SELECT TOP 1 e.import " _
"FROM tblrelcoms r " & _
" INNER JOIN [beant].[dbo].tblequipments e " & _
" ON r.IDEquipment = e.IDEquipment " & _
"ORDER BY e.Import;"
Using connection = new SqlConnection(sConnectionString)
Using command = New SqlCommand(sSQL, connection)
connection.Open()
TextBox1.Text = command.ExecuteScalar().ToString()
End Using
End Using
Although if you need more than one column, then you could use a data reader:
Dim sConnectionString As String _
= "User ID=XXX ;Password=XXX;Initial Catalog=gemXXX;Data Source=SCRBAMSDKBXXXXXX"
Dim sSQL as string = "SELECT TOP 1 e.import " _
"FROM tblrelcoms r " & _
" INNER JOIN [beant].[dbo].tblequipments e " & _
" ON r.IDEquipment = e.IDEquipment " & _
"ORDER BY e.Import;"
Using connection = new SqlConnection(sConnectionString)
Using command = New SqlCommand(sSQL, connection)
connection.Open()
Using reader = command.ExecuteReader()
If reader.Read()
TextBox1.Text = reader.GetString(0)
End If
End Using
End Using
End Using
I have made a couple of other changes too.
Added Using blocks to ensure IDisposable objects are disposed of properly.
Updated the sql join syntax from ANSI 89 implicit joins to ANSI 92 explicit joins, as the name suggests the syntax you are using is 24 years out of date. There are many reasons to start using the new syntax, which is nicely covered in this article: Bad habits to kick : using old-style JOINs
Added an ORDER BY clause to your sql. TOP 1 without order by will give you indeterminate results (unless you only have one record, in which case top 1 is redundant)
A more complex solution would be to use output parameters, which will work and seems more in line with what you were originally trying to achieve, but is overkill for this situation (in my opinion):
Dim sConnectionString As String _
= "User ID=XXX ;Password=XXX;Initial Catalog=gemXXX;Data Source=SCRBAMSDKBXXXXXX"
Dim sSQL as string = "SELECT TOP 1 #Output = e.import " _
"FROM tblrelcoms r " & _
" INNER JOIN [beant].[dbo].tblequipments e " & _
" ON r.IDEquipment = e.IDEquipment " & _
"ORDER BY e.Import;"
Using connection = new SqlConnection(sConnectionString)
Using command = New SqlCommand(sSQL, connection)
connection.Open()
Dim p As SqlParameter = command.Parameters.Add("#Output", SqlDbType.VarChar, 255)
p.Direction = ParameterDirection.InputOutput
command.ExecuteNonQuery();
TextBox1.Text = p.Value.ToString()
End Using
End Using
*Please excuse any syntax errors, I have not used VB.Net in years, and some c# quirks may be in the below, such as I can't remember if you just don't have to use parentheses for a parameterless method, or if you can't... Hopefully there is enough basic structure to get you started

Related

SQL INNER JOIN Syntax works on Access but not on VBA

I am trying to import data from my Access database in a VBA form using a button and a gridview. I tested the code in Access and it worked, but for some reason it doesn't work when I try to implement it in VBA button. I get the error "No value given for one or more required parameters". Can you tell me please what am I doing wrong?
This is the code (I translated it to English, so maybe I forgot to modify something, but I repeat that it worked on Access):
Dim conn As OleDbConnection = New OleDbConnection
Dim provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="
Dim dataFile = "C:\Users\solov\Downloads\LibrarieV2.accdb"
conn.ConnectionString = provider & dataFile
conn.Open()
Dim q = "SELECT Customers.gender, Books.book_category, " & _
" SUM(Details_sales.total_cost) AS TotalSumCategory " & _
" FROM ((Customers INNER JOIN Sales ON Customers.customer_id = " & _
" Sales.customer_id )INNER JOIN Details_sales ON Sales.sale_id = " & _
" Details_sales.sale_id) INNER JOIN Books ON Details_sales.isbn = " & _
" Books.isbn GROUP BY Customers.gender, Books.book_category, " & _
" TotalSumCategory ORDER BY Books.book_category"
Dim cmd As OleDbCommand = New OleDbCommand(q, conn)
Dim da As New OleDbDataAdapter(q, conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
Dim ds = New DataSet
da.Fill(ds, "Categories") ---> this is the chart that I will use to populate the grid
DataGridView1Form2.DataMember = "Categories"
DataGridView1Form2.DataSource = ds

"Operation must be an updateable query" VB.Net OleDB for Excel

Ive been trying to find a solution for this problem without any success:
I'm using VB.NET and I need to read and update records from an Excel file. I use the OleDB API for that. It works fine for all the reading, but impossible to write to the file (Update or Insert queries)
Here is what I have:
My connection string:
Public connString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\...\Resources\attempt.xls;Extended Properties='Excel 8.0;HDR=YES;IMEX=1;'"
Select query that works fine:
Dim checkQuery = "SELECT * FROM [Sheet1$] WHERE [TravellerPN] = #T"
Try
Using connection As New OleDb.OleDbConnection(Form.connString)
Dim checkCommand As New OleDbCommand(checkQuery, connection)
checkCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
connection.Open()
Dim reader As OleDbDataReader = checkCommand.ExecuteReader()
Dim path As String = ""
While reader.Read()
path = reader("Datapath").ToString
End While
reader.Close()
MsgBox(PN & " " & DP & " " & path,,)
If a record for the part number entered doesnt exist, and nothing is returned, insert a new line
If path = "" Then
Dim addQuery = "INSERT INTO [Sheet1$] ([TravellerPN],[Datapath]) VALUES (#T, #D)"
Dim addCommand As New OleDbCommand(addQuery, connection)
addCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
addCommand.Parameters.Add("#D", OleDbType.VarChar).Value = DP
Dim rows As Integer = addCommand.ExecuteNonQuery()
And this was where it returns the error.
MsgBox(rows & " row added!",, "") 'Never diplayed
And other query that doesn't work either:
Else 'If does exist, confirm replacement'
Dim replaceResponse = MsgBox("A path already exists for " & PN & "." & vbNewLine & "Do you want to replace " & path & " with " & DP & "?", MsgBoxStyle.YesNo, "Overwrite previous datapath?")
Dim replaceQuery = "UPDATE [Sheet1$] SET [Datapath] = #D WHERE [TravellerPN]=#T"
Dim replaceCommand As New OleDbCommand(replaceQuery, connection)
replaceCommand.Parameters.Add("#D", OleDbType.VarChar).Value = DP
replaceCommand.Parameters.Add("#T", OleDbType.VarChar).Value = PN
Dim rows As Integer = replaceCommand.ExecuteNonQuery()
MsgBox(rows & " row updated!",, "")
End If
connection.Close()
End Using
I've tried to fix the issue: it could be caused by permissions, so I authorized even guests accounts to modify my folder.
If it were a ReadOnly mode in the connection: I tried adding Mode=ReadWrite but my connection String didn't work after that. (That option seems only available for ADO connections?)
I tried running the app as administrator
And finally, I'm posting this here hoping to get some help.
Sorry or the long post, I was trying to give all the elements that could potentially be a problem.
Thanks.

VB.net Checking if database exists before connecting to it

I found the following query in order to find out if a database table was created already or not:
if db_id('thedbName') is not null
--code mine :)
print 'db exists'
else
print 'nope'
Now I am wanting to use that same query within my VB.net application. This is the code I currently have elsewhere that connects to the database (that I am wanting to see if its there before doing all this):
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Initial Catalog=thedbName;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Of course the issue with this is that I have to know the database name first in order to connect to the database.
I then seem to be able to connect to the master database using this:
Dim cn As SqlConnection = New SqlConnection("Data Source=DAVIDSDESKTOP;" & _
"Integrated Security=True;" & _
"Pooling=False")
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"Print() 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"Print() 'nope'"
Dim cmd As SqlCommand = New SqlCommand(sql, cn)
cmd.Connection.Open()
Dim blah As String = cmd.ExecuteNonQuery()
cmd.Connection.Close()
But that query seems to throw an error on Dim blah As String = cmd.ExecuteNonQuery() of:
Additional information: Incorrect syntax near ')'.
So I'm not all sure what I am missing in order to correct the issue with the query?
Need to know how to have the query come back and say 'exists' or 'nope'
Change Print() to Print (remove the parentheses.)
Better, don't use Print at all, use select.
Dim sql As String = "if db_id('thedbName') is not null " & vbCrLf & _
"select 'exists' " & vbCrLf & _
"else " & vbCrLf & _
"select 'nope'"
Dim blah As String = CType(cmd.ExecuteScalar(), string)
ExecuteNonQuery returns the number of affected rows for updates and inserts. But what you are executing is a query.
ExecuteScalar returns the first column of the first row selected. The query above only returns one row with one value, so that's what it will return.
or do it like this
select * from sys.databases where [name] = 'thedbName'
if it returns a row, then the database exists, if not then it doesn't.
To check if a table exists within a database, use this
select * from sys.objects where [name] = 'theTableName' and type_desc = 'USER_TABLE'

how to call checkbox value from sql to display on form vb.net

am doing this but not working only apply in first record its working in insert and update
i stored in sql as true or false
Sub db_load()
On Error Resume Next
Dim pringdata As String = "SELECT custcode_" & _
",custname_" & _
",custname2_" & _
",phone_" & _
",mobile_" & _
",custadd_" & _
",date_" & _
",cutomerzone_ " & _
",check_ " & _
" FROM custInfo "
Dim sqlconload As New SqlConnection(sqlcon)
sqlconload.Open()
Dim da As New SqlDataAdapter(pringdata, sqlconload)
ds.Clear()
da.Fill(ds, "custInfo")
For i As Integer = ds.Tables(0).Rows.Count = 0 To -1
If ds.Tables(0).Rows(i).Item("check_") = "true" Then
checkActive.Checked = True
Else
checkActive.Checked = False
End If
Next
sqlconload.Close()
I gather you are referring to a specific customer since you're only setting a single checkbox? You'll need to modify your query to match that.
Next, examine how you're storing the "check" column. In most cases, converting to Bool will resolve it but you may have to special case it based on available values.
Also, if the field you're looking at could be null, you'll have to account for that as well.
Here's a good pattern to follow that properly disposes of resources such as connections, commands, and readers.
Public Sub db_load()
Using cn = New SqlConnection(sqlcon)
cn.Open()
Using cmd = New SqlCommand("SELECT custcode,custname,custname2,phone,mobile,custadddate,customerzone,check FROM custInfo", cn)
Using dr = cmd.ExecuteReader()
If dr.Read Then
checkActive.Checked = CBool(dr("check"))
End If
End Using
End Using
End Using
End Sub

Using results of a SqlDataReader in a SQL query

I would like to get the results of my reader to be able to be used in a WHERE clause in another SQL command. I have tried to put the reader into a variable to use but it does not work. I've never used readers before so I do not know how they work. Can anyone give me an idea of how to get the result of the reader into there where statement? Thanks.
The code:
Dim courseSelectCom = New SqlCommand("select stuff((select ','+course_name from course where school= '" & schoolSelect & "' for xml path ('')), 1, 1, '')", connection)
Dim reader = courseSelectCom.ExecuteReader()
If reader.Read() Then
Dim courseVar As String
courseVar = "%" & reader("course_name") & "%"
Using totalStudentCom = New SqlCommand("SELECT COUNT(student_ID) FROM student " & "course_name like #course", connection)
totalStudentCom.Parameters.AddWithValue("#course", courseVar)
Dim result = totalStudentCom.ExecuteScalar()
MessageBox.Show("Students for course = " & result.ToString)
End Using
End If
There are a couple of problems here.
First you should use parametrized query and not string concatenations for building sql commands
Second when a DataReader is opened, the connection object cannot serve another command unless you have specified the substring MultipleActiveResultSets=True; in your connection string
Dim courseSelectCom = New SqlCommand("select course_name from course where school= #school", connection)
courseSelectCom.Parameters.AddWithValue("#school", schoolSelect)
Dim reader = courseSelectCom.ExecuteReader()
if reader.Read() then
Dim courseVar As String
courseVar = "%" & reader("course_name") & "%"
Using totalStudentCom = new SqlCommand("SELECT COUNT(student_ID) FROM student " & _
"course_name like #course", connection)
totalStudentCom.Parameters.AddWithValue("#course", courseVar)
Dim result = totalStudentCom.ExecuteScalar()
MessageBox.Show("Students for course = " & result.ToString)
End Using
End If
Remember that this works only if MARS is enabled