I'm learning SQL Server and VB.NET. My problem is how to select and make a condition to specific row in the table.
Like, that I have table with two columns name, age, and I want to select rows where name is "XY".
After that, make a condition with an (if) statement like: if age (in the table) larger than 20.
Do some thing or each one his name "xy" print his age in a messagebox.
You can try this in one query like this:
select * from yourtable where name = 'XY' and age > 20
Noor, Rahul was exactly correct in what was recommended. It sounds like you have little experience with how to get data from a SQL query into a useable form so you can test and manipulate or analyze data. For technology, look at ADO, and ADOX usage in VB.NET with SQL queries. My recommendation is for you to purchase one or more good books on VB.NET, so you can fully understand how to move forward.
Dim filename As String = "C:\myfile.mdb"
Dim tablename as String = "mytable"
Dim ConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data source =" & filename
Dim cn As New OleDbConnection(ConnString)
cn.Open()
Dim qry As String
Dim cmd As New OleDbCommand(qry, cn)
qry = "SELECT * FROM [" & tablename & "] WHERE name = "XY" and age > 20 ORDER by age "
cmd.CommandText = qry
cmd.Connection = cn
Dim drdata As OleDbDataReader = cmd.ExecuteReader
Dim Cnt As Integer = 0
Dim name(), age() as Object
Do While drdata.Read
Cnt += 1
Redim Preserve name(Cnt)
Redim Preserve age(Cnt)
name(Cnt) = drdata.Item("name")
age(Cnt) = drdata.Item("age")
Loop
drdata.Close()
For i As Integer = 1 to Cnt
If age(i) = 20 Then
' do anything you want here
End If
Next i
Related
I am looking for any advice on how i can read a single column in excel that contains 500 user_id's and query a database to display results in a WPF application. A user can own or rent so the SQL would look like;
SELECT * FROM users WHERE own= 'user_id' or rent= 'user_id'
This is fine for one user but i want to read each user_id and concatenate it to the SQL statement to pull out all results from the database. Any one have any easy way of doing this?
Replace the range as necessary, credit to brettdj on the join - Simple VBA array join not working
Sub test()
Dim strQuery As String
Dim strVals As String
Dim rngTarget As Range
Set rntTarget = Range("A1:A7")
Dim varArr
Dim lngRow As Long
Dim myArray()
varArr = rntTarget.Value2
ReDim myArray(1 To UBound(varArr, 1))
For lngRow = 1 To UBound(varArr, 1)
myArray(lngRow) = varArr(lngRow, 1)
Next
strVals = "('" & Join$(myArray, "','") & "') "
strQuery = "SELECT * FROM users WHERE own in " _
& strVals & "or rent in " & strVals
End Sub
How can I show the last row of data in database?
I have this code here but it only shows the first data row in database
Dim cnPodaci AsNew SqlConnection
cnPodaci.ConnectionString = "your connection string"
cnPodaci.Open()
Dim cm AsNew SqlCommand
cm.CommandText = "SELECT * FROM TABLE"
cm.Connection = cnPodaci
Dim dr As SqlDataReader
dr = cm.ExecuteReader
If dr.HasRows Then
dr.Read()
txtBox1.text = dr.Item("ColumnName1")
txtBox2.text = dr.Item("ColumnName2")
dr.Close()
EndIf
cnPodaci.Close()
You may add an "ORDER BY" to your sql. Like
cm.CommandText = "SELECT * FROM TABLE ORDER BY XX desc"
Assuming XX is the name of the column which increases for every new row.
Edit:
consider:
cm.CommandText = "SELECT * FROM TABLE ORDER BY XX desc limit 1"
It will return the last row, having chosen what XX is.
So basically I'm trying to write the below code to the database and I have the primary key as an Int and it was autogen but when writing to the database it didnt allow me to do it kept telling me that I wasn't allowed to enter a null value (because the code is obviously not writing to the primary key field) so I used the line
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
But the problem is I have to change the value each time I want to test a new record i.e. 1,2,3,4 and so on. I was wondering is there a line of code I can put in to make it create a value by adding +1 each time so I don't need to go into the code and enter a new number each time. Below is the full code writing to the database so you can see a better view of it
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim recordsAffected As String
Dim cmdstring As String = "INSERT [Event Table](EventID, EventTypeID, EventName, VenueName, NumberOfGuests, Date, ClientAddress, WeddingName, BuildingAddress) Values(#EventID, #EventTypeID, #EventName, #VenueName, #NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress)"
Con = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\YellowDoor.mdf;Integrated Security=True;User Instance=True")
cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventID", SqlDbType.Int).Value = 3
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
cmd.Parameters.Add("#EventName", SqlDbType.Text).Value = EventNametxt.Text
cmd.Parameters.Add("#VenueName", SqlDbType.Text).Value = VenueLoDD.SelectedValue
cmd.Parameters.Add("#NumberOfGuests", SqlDbType.Int).Value = CInt(NumOfGtxt.Text)
cmd.Parameters.Add("#Date", SqlDbType.Int).Value = CInt(DateTxt.Text)
cmd.Parameters.Add("#ClientAddress", SqlDbType.Text).Value = txtAddress.Text
cmd.Parameters.Add("#WeddingName", SqlDbType.Text).Value = txtWedding.Text
cmd.Parameters.Add("#BuildingAddress", SqlDbType.Text).Value = txtBAddress.Text
Con.Open()
recordsAffected = cmd.ExecuteNonQuery
Con.Close()
If your EventID is an IDENTITY column, you should never try to set a value for it.
Just ignore that field both as parameter or inside the INSERT command.
And you can retrieve the value assigned by the database engine to your field in this way
Dim Con As SqlConnection
Dim cmd As SqlCommand
Dim cmdstring As String = "INSERT [Event Table] " & _
"(EventTypeID, EventName, VenueName, NumberOfGuests, [Date], ClientAddress, " & _
"WeddingName, BuildingAddress) Values(#EventTypeID, #EventName, #VenueName, " & _
"#NumberOfGuests, #Date, #ClientAddress, #WeddingName, #BuildingAddress); " & _
"SELECT SCOPE_IDENTITY()"
Using Con = New SqlConnection(".....")
Using cmd = New SqlCommand(cmdstring, Con)
cmd.Parameters.Add("#EventTypeID", SqlDbType.Text).Value = EventTypeDD.SelectedValue
.....
Con.Open()
Dim result = cmd.ExecuteScalar()
if result IsNot Nothing Then
Dim newEventID = Convert.ToInt32(result)
....
End If
End Using
End Using
With this code you don't pass anything for the EventID field but you add a second command text to your query. This second command will return the last value generated for an IDENTITY column by the database for your connection. This double command (A.K.A. batch commands) is executed using ExecuteScalar because we are interested in the single value returned by the SELECT SCOPE_IDENTIY()
Notice also that DATE is a reserved word in T-SQL so it is possible to use it as name of a column only if you enclose it in square brackets
I'm trying to get my program to generate new identifications based on the highest ID-number already within the database.
Dim kobling As New Tilkobling
Dim hentOrdreNummer As String = "SELECT MAX(ordreID) FROM bestilling"
Dim svar As DataTable
bOrdreID = hentOrdreNummer + 1
kobling.sporring(user, password, hentOrdreNummer)
svar = kobling.hentData()
All this returns is, ofcause, the sql-command (with the +1 it crashes due to string/integer i assume). Is there a simple way to do this?
New Code:
Dim kobling As New Tilkobling
Dim hentOrdreNummer As String = "SELECT * FROM bestilling"
Dim svar As DataTable
kobling.sporring(user, password, hentOrdreNummer)
svar = kobling.hentData()
Dim temprad As DataRow
Dim nyID, modID As String
For Each temprad In svar.Rows
nyID = temprad("ordreID")
modID = nyID + 1
bOrdreID = modID
This works, tho, It starts with the lowest number, and I get a error message untill it reach a number thats not already taken.
Working Code:
Dim kobling As New Tilkobling
Dim hentOrdreNummer As String = "SELECT MAX(ordreID) AS ordreID FROM bestilling"
Dim svar As DataTable
kobling.sporring(user, password, hentOrdreNummer)
svar = kobling.hentData()
Dim temprad As DataRow
Dim nyID, modID As String
For Each temprad In svar.Rows
nyID = temprad("ordreID")
modID = nyID + 1
bOrdreID = modID
Try this:
SELECT IFNULL(MAX(ordreID),0)+1 FROM bestilling
It will return the new possible ID i.e., max(id)+1.
You need to establish a connection to a database and actually run your SQL against it.
You then create a variable to store your result in and + 1 to your result.
You can not simply declare a string of "SELECT . . . . " and then expect to add + 1 to it.
I am vba code beginner. I am writing a vba code to extract data from mysql database. I have made successful connection with mysql server. Basically, database has 4 fields such as id, id_id, descr and notation.
I am trying to populate the combobox in userform by field list. Let say, I want to populate the descr list based on id_id field. I tried to create recordset as below
sqlQa = "select descr from matcat_select order by descr & id_id = int;"
FYI, id_id might be int or string.
See the code for data extraction from database and populate into Combobox
sqlQa = "select descr from matcat_select"
Where id_id = 20
Order by descr;"
'sqlQa = "select descr from matcat_select where id_id = 20;"
rs.Open sqlQa, oConn, adOpenStatic
With rs
'Set .ActiveConnection = Nothing 'Disconnect the recordset
.k = .Fields.Count
'Populate the array with the whole recordset
.vaData = .GetRows
End With
'Close the connection.
oConn.Close
'Manipulate the Combobox's properties and show the form.
With UserForm1
With .ComboBox1
.Clear
.BoundColumn = k
.List = Application.Transpose(vaData)
.ListIndex = -1
.ColumnCount = 2
End With
'.Show vbModal
End With
Please help me to solve this issues.
If you are not sure if the id_id field is an int then input it as a string by surrounding it by single quotes.
Use where clause to fetch records for matching id_id value.
Change:
sqlQa = "select descr from matcat_select
order by descr & id_id = int;"
To:
sqlQa = "select descr from matcat_select
where id_id = 'value_of_id_id_here'
order by descr;"