VB.net Query results - vb.net

I'm a bit confused on how to grab query results. With VBA i would open a record set and have the results of the query written to that recordset. IN VB.net how can I grab the query result and throw each column into specfic arrays?
dim ssql as string
ssql = " Select * from table "
Now how would I force it to query my DB? I have a connection established already.
After the query how can i play with the columnes and place them into arrays?

This is actually a pretty big topic...you might want to get an overview before you start.
http://msdn.microsoft.com/en-us/library/h0y4a0f6(v=vs.80).aspx
To answer your question: If you have a database connection you can use a DataAdapter to fill a local dataTable or dataSet.
connectionString = "Data Source=servername; Initial Catalog=databasename; " + _
"User ID=userid; Password=password"
cnn = New SqlConnection(connectionString)
cnn.Open()
sqlAdp = New SqlDataAdapter("select * from users", cnn)
sqlAdp.Fill(ds)
EDIT: This is just a sample, you'll want to close the connection and declare a dataSet 'ds'.

You should take a few minutes to read this

Related

how to sorting item in combo box by Alphabet

i use this code to fill the search result records in combo pox and it working good ..
da = New SqlDataAdapter("Select * From MovTable where NameOfMov like '" & AlphaCB.Text & "%'", sqlcon)
da.Fill(dt0)
SearchResultCbB1.DataSource = dt0
SearchResultCbB1.ValueMember = "NameOfMov"
but i need some change to make the combo pox sorting them by Alphabet
thanks
When you attach a ComboBox's datasource to a datatable (dt0) it actually attaches to the .DefaultView DataView of the table. This means you can set the .Sort property of the view to sort the combo:
dt0.DefaultView.Sort = "[NameOfMov] ASC";
SearchResultCbB1.DisplayMember = "NameOfMov" 'this shows in the combo
SearchResultCbB1.ValueMember= "ID" 'you probably want an ID, not the movie name, for this
SearchResultCbB1.DataSource = dt0
You can change this Sort property at any time. For more info on what you can do with it, see the documentation
Please don't write SQL's like you have there; it's a massive security flaw. For more info on why, read http://bobby-tables.com - it will also give advice on how to prevent it, but really you should look at upgrading your knowledge to use Entity Framework or Dapper for your data access and never again, ever concatenate a value into an SQL string
Please always use parameters to avoid sql injection and make you your sql query strings easier to write. I had to guess the datatype and size of the parameter. Please check your database for the actual values and adjust the code.
The user interface is updated after the database objects are closed and disposed with the Using...End Using block.
Private Sub OPCode()
Dim dt0 As New DataTable
Using sqlcon As New SqlConnection("Your connection string"),
da As New SqlDataAdapter("Select * From MovTable where NameOfMov like #Name Order By NameOfMov;", sqlcon)
da.SelectCommand.Parameters.Add("#Name", SqlDbType.NVarChar, 400).Value = AlphaCB.Text & "%"
da.Fill(dt0)
End Using
SearchResultCbB1.DataSource = dt0
SearchResultCbB1.DisplayMember = "NameOfMov"
SearchResultCbB1.ValueMember = "MovieID" 'The Primary Key field in you Database
End Sub
this is an alternative right answer for my question
da = New SqlDataAdapter("Select * From MovTable where NameOfMov like '" & AlphaCB.Text & "%' order by NameOfMov ", sqlcon)
All I needed was this one addition "order by NameOfMov"
Didn't need all this hassle.

VB Access DB Update statement

I am new to this forum, please could you help me get this code to work, when i execute it, it simply does nothing and does not update the DB. If i remove the square brackets it gives an error: "SYNTAX ERROR in UPDATE statement"
Any help appreciated!
Dim connection As OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserDB.accdb;Jet OLEDB:Database;")
connection.Open()
Dim pass As String
pass = txtconfirm.Text
Dim user As String
user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= '" & pass & "' WHERE [Username]= '" & user & "';"
Dim command As New OleDbCommand(query, connection)
command.ExecuteNonQuery()
connection.Close()
Given your actual connection string, the database that will be updated is the one in the directory where your application starts. This means that if you work with a WinForms application this folder is \BIN\DEBUG or x86 variant. If there is not error then you could get the return value of the ExecuteNonQuery call to verify if a record has been updated or not
Dim rowsUpdated = command.ExecuteNonQuery()
MessageBox.Show("Record updated count = " & rowsUpdated)
If this value is not zero then your database has been updated and you are looking for changes in the wrong database. Check the one in the BIN\DEBUG folder.
In any case your code has big problems. If your variables user or pass contain a single quote, then your code will crash again because your string concatenation will form an invalid SQL. As usual the only workaround is to use a parameterized query
Dim pass = txtconfirm.Text
Dim user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= #p1 WHERE [Username]= #p2"
Using connection = New OleDbConnection("...........")
Using command As New OleDbCommand(query, connection)
connection.Open()
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = pass
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = user
command.ExecuteNonQuery()
End Using
End Using
The parameterized approach has many advantages. Your query text is more readable, there is no misunderstanding between your code and the values expected by your database engine. And while not easy to exploit with MS-Access there is no problem with Sql Injection
I think Steve presents a much better approach for you coding this...
Let me just throw out a few more things:
The reason you can't take those brackets out is some of your column names are reserved words; just FYI.
Since you report "it does nothing..." when you execute, it sounds like you have a valid connection and sql syntax, in which case my next step would be to copy the sql command text while in debug mode, change it to a select and run it in your DB. You should get one result when you do. If not, either your criteria or field contents are not what you think they are...
Just change the Update table SET field-value ... to SELECT * FROM table and leave the WHERE clause as is.

Cant save or update my SQL Server tables using vb.net

I am a complete beginner to .net and am confused at some basic things. Please help.
First of all the table I create and populate (by right clicking tables in server explorer) disappear once I restart the computer. how do I keep them.
Is there any better place/interface to type SQL queries in vb.net than the command prompt.
In the following code:
Dim cn As SqlConnection = New SqlConnection(strConnection)
cn.Open( )
' Create a data adapter object and set its SELECT command.
Dim strSelect As String = _
"SELECT * FROM Categories"
Dim da As SqlDataAdapter = New SqlDataAdapter(strSelect, cn)
' Load a data set.
Dim ds As DataSet = New DataSet( )
da.Fill(ds, "Categories")
This far the code runs fine but just to gain better understanding, I would like to ask that
while data from SQL Server database was saved into da in accordance to the query, why do we need to save/transfer it in the dataset object ds.
Is there any additional benefit of SqlCommand over SqlDataAdapter besides speed?
Dim autogen As New SqlCommandBuilder(da)
Dim dt As DataTable = ds.Tables("Categories")
' Modify one of the records.
Dim row As DataRow = dt.Select("CategoryName = 'Dairy Products'")(0)
row("Description") = "Milk and stuff"
gives an error when I use it with
da.Update(ds, "Categories")
regarding dt.select not returning any value.
What is the way out?
to answer your questions :
The tables you create with the server explorer are IN MEMORY. Same goes for dataset, they are in-memory representation of your table. As for your 2nd example, the DS you use isnt filled when you try to get the DT. hence why the DT is empty.
If your starting, I would suggest you go look into Linq-to-Sql (http://msdn.microsoft.com/en-us/library/bb425822.aspx) for a more up-to-date way of doing sql in .net ( I think its 4.0 framework)
As for the 2nd point, I'd say normally you should use store procedure for most of your sql commands .. the sqlcommand is use like this
Try
Cmd = New SqlClient.SqlCommand("st_InventoryStatus_Or_AnyStoreProcName_Or_ASqlQuery")
Cmd.CommandTimeout = 300 'not really needed'
Cmd.CommandType = CommandType.StoredProcedure 'you can type CommandType.Text here to use directly your "Select * from Category"'
Cmd.Parameters.Clear() 'just to be sure its empty, its not mandatory'
Cmd.Parameters.Add("#idCategory", SqlDbType.Int).Value = myCategory.Id 'here are the parameters of your store proc, or of your query ("select * from Category where Category.id = #Id")'
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information)
End Try

Perform Action on Each Record from SQLDataSource

I've submitted a bunch of questions as of late - but this has been a great repository of information. I'm a .NET nub, as you can see, so if I'm missing basics or information please let me know and I'll try and fill in the gaps.
I'm using ASP.NET/VB.NET to create this with SQL 2005. I have a project where I'd like to take a set of records from a table, then send each one through an API, get a result and writeback the result to a table, then move to the next.
Initially, my thought was create a SQLDataSource that grabs all the records, then perform the action on a button to do the action of sending through each record.
Is there a way I can call the recordset from SQLDataSource and perform a loop? I'm thinking something like in Classic ASP/VBScript where you would open a RecordSet, do an action, then Loop until the RS was EoF.
Thanks for the help!
You can may want to put your results in a dataset. After getting the results, you can loop through the returned rows
Dim ds As Dataset = GetSomeDataFromSq
For Each dr As DataRow In ds.Tables(0).Rows
Console.WriteLine (dr("ColName"))
Next
You could also use a sqlDataReader
Using conn As sqlconnection = New sqlconnection("put conn info")
Using MyCommand As SqlCommand = New SqlCommand("SELECT ProductName FROM products", conn)
conn.Open()
Using myDataREader As SqlDataReader = MyCommand.ExecuteReader
While myDataREader.Read
Response.Write("Name: " & myDataREader.Item("ProductName"))
End While
End Using
End Using
End Using

How do you read a full table from a SQL database in VB.NET?

I hate to ask this question on this forum, but I'm having a lot of trouble finding it on these online tutorials. Basically, I'm learning about SQL, VB.NET, and how to glue the two together, and I've learned about using SqlCommand.executeScalar() to get the first entry in a table. But that's all it's really good for, right? Or is there something more to the story here?
Basically, I'm wanting to ask about how to pull in a FULL table from a SQL database while using VB.NET, as well as how to pry substrings and stuff from it. Again I'm having to ask this on this forum because all these online tutorials seem to ignore the subject completely. Thank you for you help!
Here's an example (a little more verbose than I like my code, but perhaps will help):
Dim conString As String = "data source=ServerName;" & _
"initial catalog=DBName;" & _
"integrated security=SSPI;" & _
"persist security info=false;"
Dim conSQL As New SqlConnection(conString)
conSQL.Open()
Dim cmdSQL As New SqlCommand()
cmdSQL.CommandType = Data.CommandType.Text
cmdSQL.CommandText = "SELECT FieldName1, FieldName2 FROM MyTable"
Dim adptSQL As New SqlClient.SqlDataAdapter(cmdSQL)
Dim myDataSet As New DataSet()
adptSQL.Fill(myDataSet)
conSQL.Close()
With myDataSet.Tables(0)
For rowNumber As Integer = 0 To .Rows.Count - 1
With .Rows(rowNumber)
Console.WriteLine(String.Format("Field1: {0}, Field2: {1}", _
.Item(0).Value.ToString, _
.Item(1).Value.ToString))
End With
Next
End With
Basically, one of the options SLaks mentioned above.
You have two options:
Use a SqlDataAdapter object to fill a DataTable from a SELECT command.
This is the more flexible method; you can loop or query the DataTable at will, or bind it to a grid control.
Call ExecuteReader on a SqlCommand to get a SqlDataReader object that reads the rows in a SELECT statement one at a time.