Get last UserID from SqlServer to textbox control - vb.net

I have a table customers where each cust has UserID as "A000" now I need to get the last entered ID from the database and display it in my textbox.
Can anyone suggest me how do I do this?
As I have seen many articles describing about
SELECT ##IDENTITY
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT('TableName')
but unable to know where to use it correctly.
And here is how I'm doing it :
Dim strConnection As String = "Data Source=.\SqlExpress;Initial Catalog=Subscription;Integrated Security=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 da As New SqlDataAdapter("SELECT MAX(UserID) FROM Customers", con)
Dim cmd As New SqlCommandBuilder(da)
da.Fill(dtusers)
con.Close()

Use ExecuteScalar :
Dim comm as new SqlCommand
comm.CommandText = "SELECT MAX(UserID) FROM Customers"
comm.Connection = con
Dim MaxUserID as object = comm.ExecuteScalar()
Use the ExecuteScalar method to retrieve a single value (for example,
an aggregate value) from a database
Side Note : ExecuteScalar() may return a null reference (Nothing in VB.NET) if the result of the command is empty like when there are no records in the table or there is condition that doesn't produce any records. Make sure you check that before assigning the value to your TextBox.

Related

I am trying to find out how to compare two dates in a visual basic database

I currently have a visual basic database made in Microsoft access. In this database, I allow the user to enter a date in a text box and this date gets saved to the database. I want to compare the dates "on the database!". The hard part is that the dates are entered in the same text box but saved on different rows. I need to compare the different dates in the rows of the database.
Fetch data from the database and use FOR EACH loop to compare. A sample code is as follows:
Dim con = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;DataSource=Test.accdb;Persist Security Info=False;")
con.Open()
Dim cmd As New OleDbCommand("SELECT date_col FROM my_table", con)
cmd.CommandType = CommandType.Text
Dim reader As OleDbDataReader = cmd.ExecuteReader()
Dim dt As DataTable = reader.GetSchemaTable()
For Each row As DataRow In dt.Rows
If row.Item("date_col") = **your_criteria** Then
**your_other_statements**
End if
Next row
con.Close()
Hope this will help

VB.Net and Access - Getting Totaliser Value

I'm trying to databind a textbox to a totaliser value in an access database. I currently update the database via OleDbCommand and then edit any existing entries via databinding on the form.
I have everything working fine, but I want a textbox to show the totaliser (sum) of a particular column in the datbase. Access shows this totaliser underneath the column if the database is opened.
Is there a method to bind this value to the textbox?
Thanks
Well, however you are accessing the database, you need to make a call to get the SUM of your desired table.
If we are talking about SQL, it would look something like:
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = " SELECT SUM(total) AS Total From YourTable"
cmd.CommandText = sSQL
OleDbDataReader dr = cmd.ExecuteReader()
If dr.Read() Then
set total = Convert.ToInt32(dr["Total"])
End If
You could load this into a DataTable/DataSet or use the DataReader and assign the result (the sum) to a textbox, like:
TextBox1.Text = total
If you are using Linq it could look like (this is just an example):
Dim yourObject = From cust In db.Customers
Group By cust.City
Into Average(cust.Orders.Count)
Order By Average
DataGridView1.DataSource = yourObject

syntax error in from clause. vb 2012

Dim con As New OleDbConnection
Dim dt As New DataTable
Dim ds As New DataSet
con.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\MedicalSys.accdb"
con.Open()
ds.Tables.Add(dt)
Dim da As New OleDbDataAdapter
da = New OleDbDataAdapter("SELECT * FROM Add Form", con)
da.Fill(dt)
Dim newRow As DataRow = dt.NewRow
That's my code but when i run it this line will give me an error:
da.Fill(dt)
I dont know exactly what the problem is!
The correct syntax for the simplest SELECT clause is
SELECT <list of fields comma separated> FROM <tablename>
So your query is not syntactically correct
It should be
SELECT * FROM ????
We don't know the table name that you want to read, so when you have found the correct table name replace the question marks with your table. Keep in mind that if the table name contains space you need to encapsulate the name with square brackets (I.E. [My Table Name])
In addition to Steve:
If your table name contains spaces or any reserved word, you need to put the table name inside brackets like:
da = New OleDbDataAdapter("SELECT * FROM [Add Form]", con)
Here I assume, that your table is named Add Form.

vb.net sqlclient insert output

I have a ms sql table PRODUCTS.
And it has three columns ID (int),NAME (nvarchar),TSTAMP (timestamp)
I want to get new inserted row's both id and timestamp (like multiple select scope_identity).
I can achieve that in sql as following:
INSERT INTO PRODUCTS (NAME)
OUTPUT inserted.ID,inserted.TSTAMP
VALUES ('Example Product')
But how can i read it in vb.net with sqlclient.sqlcommad on insertation? Which function of sqlcommand do i have to use and how? ExecuteReader maybe?
Using the ExecuteReader() method of SqlCommand would work the same as with SELECT.
OUTPUT clause works like a SELECT statement but its usage differs in
INSERT, UPDATE and DELETE commands
Here's a sample code. Try it.
Dim connString As String = "server=Test; database=Test;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
Dim cmdString As String = "INSERT INTO PRODUCTS (NAME) " + _
"OUTPUT inserted.ID,inserted.TSTAMP " + _
"VALUES ('Example Product')"
Dim cmd As New SqlCommand(cmdString, conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
conn.Close()
Here're some links
Running The OUTPUT Clause From C#
Implementing the OUTPUT Clause in SQL Server 2008

Is it possible to insert an entire VB.NET DataTable into a SQL Server at once

I have a SQLClient.DataSet in VB.NET, and I want to insert the entire thing into a SQL Server table without having to do the following:
For Each dr as Datarow in MyDataset
Dim sc As New SqlCommand("INSERT INTO MyNewTable " & _
"VALUES (#column1, #column2)", MyDBConnection)
sc.Parameters.AddWithValue("#column1", dr.Item(0))
sc.Parameters.AddWithValue("#column2", dr.Item(1))
sc.ExecuteNonQuery()
Next
Since I've got close to a million rows (all pretty skinny, so it's not much space), I obviously don't want to run this loop and generate a million INSERT statements.
I know that one option is to use a linked server when I initially fetch the data, since it's coming from another SQL Server, and just have it to the INSERT from there. However, if I already have the data in my application, is there a more efficient way to bulk insert it? Can I somehow pass the DataTable as a parameter to SQL Server and have it sort it out and insert the rows?
try with SqlBulkCopy
With SQL Server 2008 you can use Table-Valued Parameters:
Dim sc As New SqlCommand(
"INSERT INTO MyNewTable (field1, field2,...)"&
"SELECT field1, field2,... FROM #MyTable;", MyDBConnection)
sc.Parameters.AddWithValue("#MyTable", MyDataset)
sc.ExecuteNonQuery()
Use the SqlDataAdapter's InsertCommand to define your Insert query. Then call the DataAdapter's Update Method with your dataset as a parameter to have it push the data.
Something like:
Dim DA As SqlDataAdapter = New SqlDataAdapter
Dim Parm As New SqlParameter
DA.InsertCommand = New SqlCommand("Insert Into tbl1(fld0, fld1, fld2) Values(#fld0, #fld1, #fld2)", conn)
Parm = DA.InsertCommand.Parameters.Add(New SqlParameter ("#fld0", NVarChar, 50, "fld0"))
Parm = sqlDA.InsertCommand.Parameters.Add(New SqlParameter ("#fld1", SqlDbType.NVarChar, 50, "fld1"))
Parm = sqlDA.InsertCommand.Parameters.Add(New SqlParameter ("#fld2", SqlDbType.NVarChar, 50, "fld2"))
DA.Update(dataset1, "tbl1")
You could call .WriteXML() on the DataSet and dump that into the database in one insert.
A way simplier way is to use a table adapter. Then you can use the Fill method to give a datatable as argument :
Dim oStronglyTypedTable As StronglyTypedDataTable = GetTable() 'A custom function that creates your table from wherever you want)
If Not oStronglyTypedTable Is Nothing Then
Using oAdapter As New StronglyTypedTableAdapter
Dim res As Integer = oAdapter.Update(oStronglyTypedTable)
MsgBox(res & " rows have been updated.")
End Using
End If
Do not forget to change your Database "Copy to Output Directory" property to "Do net copy" and set your connection string properly...