retrieving data in VB from SQL - database

I use Visual Basic 2010 and Microsoft SQL Server 2008. I have my database and my table and i made the connection (at least i think i did) in VB using only the interface.
What i want to know is how to get data from the database and use it into my VB project. I have of course searched for solutions already but the differences i find only confuse me more. What i need to know are the basics, the tools/objects and procedures to retrieve the data.
What i try to do at the moment is make a simple selection and put that data into a listbox right when the program starts, like this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlConnection1.Open()
SqlConnection1.Close()
End Sub
End Class

1) Create your connection string
Dim connectionString As String = "Data Source=localhost;........."
2) Connect to your Database
Dim connection As New SqlConnection(connectionString)
conn.Open()
3) Create a Command and the query
Dim command As New SqlCommand("SELECT * FROM Product", connection)
Dim reader As SqlDataReader = command.ExecuteReader() //Execute the Query
4) Retrieve your result. There are several ways
Dim dt As New DataTable()
dt.Load(reader)
'Close the connection
connection.Close()
5) Bind to your list box
myListBox.ItemSource = dt
Full code here
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand("Select * from Products", connection)
command.Connection.Open()
SqlDataReader reader = command.ExecuteReader()
End Using
For more info
SQLCommand

SqlConnection1.Open()
using table As DataTable = New DataTable
using command as SqlCommand = New SqlCommand("SELECT blah blah", SqlConnection1)
using adapter As SqlDataAdapter = new SqlDataAdapter(command)
adapter.Fill(table)
end using
end using
for each row As DataRow in table.Rows
' add each listbox item
listbox1.Items.Add(row("column name"))
next
end using
SqlConnection1.Close()

Related

SqlDataAdapter not filling data table with SQL Where Clause

Attempting to fill a data table using SqlDataAdapter with a WHERE clause but it returns nothing. The SQL command itself returns data from SSMS and removing just the WHERE clause in code fills data table as expected.
Dim adapter As New SqlDataAdapter
Dim datatable As New DataTable
Using cnn As New SqlConnection(connectionString)
cnn.Open()
adapter = New SqlDataAdapter("SELECT * FROM [MyProjectDtbl] WHERE zipcode = 22021", cnn)
adapter.Fill(datatable)
adapter.Dispose()
End Using
Digging through the Select command EventSink, I found:
Unable to cast object of type 'System.Data.SqlClient.SqlInternalConnectionTds' to type 'System.Data.SqlClient.SqlInternalConnectionSmi'
Try it with parameters.
Private Sub OPCode()
Dim dt As New DataTable
Using cnn As New SqlConnection(connectionString),
cmd As New SqlCommand("SELECT * FROM [MyProjectDtbl] WHERE zipcode = #zip", cnn)
cmd.Parameters.Add("#zip", SqlDbType.Int).Value = 22021
cnn.Open()
dt.Load(cmd.ExecuteReader)
End Using
Debug.Print(dt.Rows.Count.ToString)
End Sub

SQL Server query parameter for copy data table to another table form ListView VB.net

I'm using VB.net 2013 and SQL Server Express. I want to copy data from the table that appears in the listview to the temporary table. But I got an error:
Operator '&' is not defined for types 'String' and 'System.Windows.Forms.ListViewItem.ListViewSubItem'
What are the correct parameters?
My code looks like this
For Each itm As ListViewItem In ListViewMasterBiaya.CheckedItems
Dim SIMPAN As String = "INSERT INTO TempEntriBiaya WHERE NoKode='" & ListViewMasterBiaya.SelectedItems(0).SubItems(0) & "'"
CMD = New SqlCommand(SIMPAN, CONN)
CMD.ExecuteNonQuery()
Next
End Sub
I also include the image as below, when I check it, the data will also copy to the temporary table
Comments and explanation in-line. Following LarsTech comments.
Dim SIMPAN As String = "INSERT INTO TempEntriBiaya (Column1Name, Column2Name) Values (#Column1, #Column2);"
'The Using...End Using blocks ensure that your ADO objects are closed and
'disposed event if there is an error
Using cn As New SqlConnection("Your connection string")
'The command and parameters only need to be declared once
'outside the loop, only the value of the parameters change
Using cmd As New SqlCommand(SIMPAN, cn)
cmd.Parameters.Add("#Column1", SqlDbType.Int)
cmd.Parameters.Add("#Column2", SqlDbType.VarChar)
'Open the connection at the last possible moment
cn.Open()
For Each itm As ListViewItem In ListViewMasterBiaya.CheckedItems
cmd.Parameters("#Column1").Value = itm.SubItems(0).Text
cmd.Parameters("#Column2").Value = itm.SubItems(1).Text
cmd.ExecuteNonQuery()
Next
End Using
End Using
EDIT Use event ListView.ItemChecked
Private Sub ListViewMasterBiaya_ItemChecked(sender As Object, e As ItemCheckedEventArgs) Handles ListViewMasterBiaya.ItemChecked
'e.Item returns the ListViewItem that changed its check
If e.Item.Checked = True Then
Dim SIMPAN As String = "INSERT INTO TempEntriBiaya (Column1Name, Column2Name) Values (#Column1, #Column2);"
'The Using...End Using blocks ensure that your ADO objects are closed and
'disposed event if there is an error
Using cn As New SqlConnection("Your connection string")
Using cmd As New SqlCommand(SIMPAN, cn)
cmd.Parameters.Add("#Column1", SqlDbType.Int).Value = e.Item.SubItems(0)
cmd.Parameters.Add("#Column2", SqlDbType.VarChar).Value = e.Item.SubItems(1)
'Open the connection at the last possible moment
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End If
End Sub

Import data from Excel to SQL Server using vb.net

I am importing data from Excel into a SQL Server database using vb.net. In my Excel file, in column bNumber, there are values of different types i.e some are numbers and some are text:
Telenorx
Telenorx
8
97150219924
97150219924
97150219924
97150219924
Easypayx
92
When I select the data from Excel through OleDbCommand, it retrieves numbers correctly but text values as blank.
In Excel, the column's data type is General.
This is my code to retrieve data from Excel.
excelConn = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data
Source= " + OpenFileDialog1.FileName + ";Extended Properties=""Excel 12.0
Xml;HDR=Yes""")
Dim oleDbCommand As OleDbCommand = New OleDbCommand("Select bNumber from
[Sheet1$]", excelConn)
excelConn.open()
Dim dataReader = oleDbCommand.ExecuteReader
dataReader.read()
This is not necessarily a solution for your case yet would I did was created a SQL-Server table with bNumber as nvarchar, used SQL-Server Management Studio to export to Excel where I placed the Excel file in the bin\Debug folder of the project. Using the code below all rows returned properly (as we have a string column strings are returned).
The key here is using IMEX=1 in the connection string, Excel can be finicky, this may or may not resolve the issue.
Imports System.Data.OleDb
Public Class Operations
Public Function GetData(ByVal FileName As String) As List(Of String)
Dim valueList As New List(Of String)
Using cn As New OleDbConnection With
{
.ConnectionString = ConnectionString(FileName)
}
Using cmd As OleDbCommand = New OleDbCommand("SELECT bNumber FROM [Table_1$]", cn)
cn.Open()
Dim reader As OleDbDataReader = cmd.ExecuteReader
While reader.Read
valueList.Add(reader.GetString(0))
End While
End Using
End Using
Return valueList
End Function
Public Function ConnectionString(ByVal FileName As String) As String
Dim Builder As New OleDbConnectionStringBuilder
If IO.Path.GetExtension(FileName).ToUpper = ".XLS" Then
Builder.Provider = "Microsoft.Jet.OLEDB.4.0"
Builder.Add("Extended Properties", "Excel 8.0;IMEX=1;HDR=Yes;")
Else
Builder.Provider = "Microsoft.ACE.OLEDB.12.0"
Builder.Add("Extended Properties", "Excel 12.0;IMEX=1;HDR=Yes;")
End If
Builder.DataSource = FileName
Return Builder.ConnectionString
End Function
End Class
Form code
Private Sub Button3_Click(sender As Object, e As EventArgs) _
Handles Button3.Click
Dim ops As New Operations
Dim fileName As String = IO.Path.Combine(
AppDomain.CurrentDomain.BaseDirectory, "Downloaded.xlsx")
Dim valueList As List(Of String) = ops.GetData(fileName)
For Each value As String In valueList
Console.WriteLine(value)
Next
End Sub
Results in the IDE Output window
Table structure
Worksheet
EDIT: The following link points to a MSDN code sample for working with SpreadSheetLight library. Once downloaded, set startup form to StackOverFlow1QuestionMixedTypesForm. Right click on the solution in solution explorer and select "Restore NuGet Packages", now build and run the project. There are two buttons on the form, first does mixed types for Sheet1 while button two is a variant of the same data laid out differently in Sheet2.
Code sample https://code.msdn.microsoft.com/Alternate-methods-to-work-4c52c4a2

Simple select query not working with vb.net while delete query works fine

I am writing a simple SQL Server query operation through vb.net application. I am having some strange problems.
This line is giving error:
dr = cmd.ExecuteReader()
This is giving me error "Invalid column name abhishek." Here abhishek is the data I am providing in TextBox1.Text. I am not able to think of any mistake by my side as this is a simple query. I am able to run other queries, like delete queries, on same table in a different form, so its not a database problem.
Any clue what's going wrong?
reginfo is the table name. name is one of the fields.
My complete code is below:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form9
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cmd.CommandText = "select * from reginfo where name=" + (TextBox1.Text) + ""
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader() '<<< This line is creating problem
If dr.Read() Then
TextBox2.Text = dr(0).ToString()
End If
con.Close()
End Sub
Private Sub Form8_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data Source=ABHISHEK-PC\SQLEXPRESS;Initial Catalog=locserver;Integrated Security=True;Pooling=False"
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
End Sub
End Class
if the name field is a text field then you need to enclose your textbox in single quotes, but this is bad advice to give. The only good approach to this kind of situations is through a parameterized query
cmd.CommandText = "select * from reginfo where name=#name"
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader()
Also, do not keep global objects like a connection or a command. It is always a good practice to instantiate a connection as late as possible and close it as soon as possible, better inside a Using block
Using con = New SqlConnection(...connection string here....)
Using cmd = New SqlCommand("select * from reginfo where name=#name", con)
con.Open()
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Using dr = cmd.ExecuteReader
'.... do you reading
End Using
End Using
End Using
In this way the connection is kept open for the minimum time possible and, also in case of exceptions is closed and disposed appropriately.

how to get the last userID from a database into textbox in asp.net

Thanks I used the MAX statement and it doesn't return an error but still don't understand why it isn't working. My code is shown below:
Protected Sub txtuserID_TextChanged(sender As Object, e As System.EventArgs) Handles txtuserID.TextChanged
Dim strConnection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=E:\LostPropertyProject\App_Data\LostPropertyDatabase.mdf;Integrated Security=True;User Instance=True"
'Establish SQL Connection
Dim con As New SqlConnection(strConnection)
'Open database connection to connect to SQL Server
con.Open()
'Data table is used to bind the resultant data
Dim dtusers As New DataTable()
'Create a new data adapter based on the specified query.
Dim comm As New SqlCommand
comm.CommandText = "SELECT MAX(UserID) FROM tblUser"
comm.Connection = con
Dim MaxUserID As Object = comm.ExecuteScalar()
con.Close()
End Sub
Also, I want the userID to be displayed in the textbox as soon as the page loads. How do I go about doing that? and thank you to everyone who replied to my question :) much appreciated
SELECT MAX(UserId) FROM User
This will give you the latest user id from the table.

Resources