Getting Primary key values (auto number ) VB - vb.net

I have a database on Access and I want to insert into 2 tables
ReportReq
req_sysino
I want to get the last value of primary key (auto numbered) and insert it into req_sysino
, I am stuck with this code and I dont know how to proccess
Private Function InsertSysInvToDB(intSysInv As Integer) As Integer
Dim strSQLStatement As String = String.Empty
Dim intNoAffectedRows As Integer = 0
Dim con As New OleDb.OleDbConnection("PROVIDER = Microsoft.ace.OLEDB.12.0; Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb")
Dim cmd As OleDb.OleDbCommand
Dim reqnum As String = "Select ##REQ_NUM from ReportReq"
strSQLStatement = "INSERT INTO req_sysino (Req_num, sysinvo_ID)" +
" VALUES (" & reqnum & "','" & intSysInv & ")"
cmd = New OleDb.OleDbCommand(strSQLStatement, con)
cmd.Connection.Open()
intNoAffectedRows = cmd.ExecuteNonQuery()
cmd.Connection.Close()
Return intNoAffectedRows
End Function
this is my insert code that should generate autonumber
Dim dbProvider = "PROVIDER = Microsoft.ace.OLEDB.12.0;"
Dim dbSource = " Data Source = C:\Users\felmbanF\Documents\Visual Studio 2012\Projects\WebApplication3\WebApplication3\App_Data\ReportReq.accdb"
Dim sql = "INSERT INTO ReportReq (Emp_EmpID, Req_Date,Req_expecDate,Req_repnum, Req_name, Req_Descrip, Req_columns, Req_Filtes, Req_Prompts)" +
"VALUES (#reqNUM,#reqName,#reqDescrip,#reqcolumns,#reqfilters,#reqprompts)"
Using con = New OleDb.OleDbConnection(dbProvider & dbSource)
Using cmd = New OleDb.OleDbCommand(sql, con)
con.Open()
cmd.Parameters.AddWithValue("#EmpID", txtEmpID.Text)
cmd.Parameters.AddWithValue("#reqDate", DateTime.Today)
cmd.Parameters.AddWithValue("#reqExpecDate", DateTime.Parse(txtbxExpecDate.Text).ToShortDateString())
cmd.Parameters.AddWithValue("#reqNUM", txtRep_NUM.Text)
cmd.Parameters.AddWithValue("#reqName", txtRep_Name.Text)
cmd.Parameters.AddWithValue("#reqDescrip", txtbxRep_Desc.Text)
cmd.Parameters.AddWithValue("#reqcolumns", txtbxColReq.Text)
cmd.Parameters.AddWithValue("#reqfilters", txtbxFilReq.Text)
cmd.Parameters.AddWithValue("#reqprompts", txtbxPromReq.Text)
cmd.ExecuteNonQuery()
End Using
End Using

Immediately after you ExecuteNonQuery() your INSERT INTO ReportReq ... statement you need to run a
SELECT ##IDENTITY
query and retrieve its result, like this
cmd.ExecuteNonQuery() ' your existing statement to run INSERT INTO ReportReq
cmd.CommandText = "SELECT ##IDENTITY"
Dim newAutoNumberValue As Integer = cmd.ExecuteScalar()

Related

My SQL select query with condition using list in VB.net

I have a MySQL table (variable- exchange) with a column name "symbol" and I have a list of string named "listfinalselection". I want to select all rows where the list contains the cell value of column "symbol". But I got a error that there is an error in my SQL syntax. I can't understand that error. Please help. `
Dim mysqlconn As MySqlConnection
mysqlconn = New MySqlConnection
mysqlconn.ConnectionString = "server=localhost;user id=root;password=1234;database=Share"
mysqlconn.Open()
Dim sql As String = "SELECT * FROM " & exchange & " WHERE Symbol in (" & String.Concat(",", listfinalselection.Select(Function(i) $"'{i}'").ToArray()) & ");"
Dim adapter As New MySqlDataAdapter(sql, mysqlconn)
Dim datatable As New DataTable()
adapter.Fill(datatable)
DataGridView1.DataSource = datatable
DataGridView1.Refresh()
Dim ii As Integer = 0
For Each rw As DataGridViewRow In DataGridView1.Rows
Try
DataGridView1.Rows(ii).Cells(11).Value = listeleventh(listsymbol.IndexOf(DataGridView1.Rows(ii).Cells(3).Value.ToString))
Catch
End Try
ii = ii + 1
Next
End Sub `
Here's how we can properly and securely query MySQL for a list of values:
Dim con = New MySqlConnection("server=localhost;user id=root;password=1234;database=Share")
'NOTE WELL: you still have to make sure that exchange contains no SQL!
Dim cmd As New MySqlCommand("SELECT * FROM " & exchange & " WHERE Symbol in (", con)
For i as Integer = 0 to listfinalselection.Count - 1
cmd.Parameters.AddWithValue("#p" & i, listfinalselection(i))
cmd.CommandText &= "#p" & i & ","
Next i
cmd.CommandText = cmd.CommandText.TrimEnd(","c) & ")"
Dim adapter As New MySqlDataAdapter(cmd)
Dim dt as New DataTable
adapter.Fill(dt)
Please note, before someone quotes the "Can we stop using AddWithValue already" blog, it's irrelevant to mysql

Dynamic Sql - retrieve from Oracle

I have a form with button which should find records from Oracle database. I have three Textboxes on same form, and If text matches with values in fields of DB, Datagrid should show me this records. Here is my code:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'connect to oracle DB
Dim oradb As String = "Data Source=orcl;User Id=Lucky;Password=Example;"
Dim conn As New OracleConnection(oradb)
conn.Open()
Dim SQL As String
SQL = "SELECT * FROM MyTable WHERE 1=1"
'SQL statement for 1st textbox
If Not TxtName.Text = "" Then
SQL = SQL & " AND USER_NAME =" & TxtName.Text
End If
'SQL statement for 2nd textbox
If Not TxtSurname.Text = "" Then
SQL = SQL & " AND USER_SURNAME =" & TxtSurname.Text
End If
'SQL statement for 3rd textbox
If Not TxtAddress.Text = "" Then
SQL = SQL & " AND USER_ADDRESS=" & TxtAddress.Text
End If
'select SQL statements and retrieve data using ExecuteReader
Dim cmd As New OracleCommand(SQL, conn)
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Sub
What am I doing wrong, nothing happens when button clicked?
This is a non-tested sample of the direction you could try:
Private Sub populateDataGridView()
'connect to oracle DB
Const connectionString As String = "Data Source=orcl;User Id=Lucky;Password=Example;"
Using conn As New OracleConnection(connectionString)
conn.Open()
Using cmd As New OracleCommand()
Dim SQL As String = "SELECT * FROM testtable "
Dim conjunction As String = " Where "
'SQL statement for 1st textbox
If Not TxtName.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " USER_NAME like :username")
cmd.Parameters.Add(New OracleParameter("username", String.Concat("%", TxtName.Text, "%")))
conjunction = " and "
End If
'SQL statement for 2nd textbox
If Not TxtSurname.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " user_surname like :usersurname")
cmd.Parameters.Add(New OracleParameter("usersurname", String.Concat("%", TxtSurname2.Text, "%")))
conjunction = " and "
End If
'SQL statement for 3rd textbox
If Not TxtAddress.Text.Length = 0 Then
SQL = String.Concat(SQL, conjunction, " user_address like :useraddress")
cmd.Parameters.Add(New OracleParameter("useraddress", String.Concat("%", TxtAddress.Text, "%")))
End If
'select SQL statements and retrieve data using ExecuteReader
cmd.Connection = conn
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
Dim dr As OracleDataReader = cmd.ExecuteReader()
Dim dt As New DataTable
dt.Load(dr)
DataGridView1.DataSource = dt
End Using
End Using
End Sub

Excel to Sql adding certain rows to sql server

cmd.CommandText = (Convert.ToString("SELECT * From [") & excelSheet) & "] Order By" & columnCompany & "OFFSET 0 ROWS FETCH NEXT 100000 ROWS ONLY "
I am trying to map data form excel to an sql table but the excel table has a lot of records in it, so I run out of memory if I try to add all of the records at once. So what I am trying to do is use this line of code
cmd.CommandText = (Convert.ToString("SELECT * From [") & excelSheet) & "] Order By B OFFSET 0 ROWS FETCH NEXT 100000 ROWS ONLY "
So that 100000 row will be added. Then I intend to clear the data table and do the same only from 100001 to 200000 and so on.
But I cant get this to work correctly, it works fine when it is just SELECT TOP 100000 FROM... but then I dont know how to get the next 100000 record. I think the Order By is where the issue is as I'm not sure how to get the correct column.
Here is my code Below
Private Sub btnMap_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnMap.Click
'Allows columns to be moved mapped in the correct order
Dim nbColumnsToTransfer As Integer = dgvMapped.Columns.GetColumnCount(1)
Dim indexes As List(Of Integer) = (From column As DataGridViewColumn In dgvLoadedata.Columns.Cast(Of DataGridViewColumn)() _
Take nbColumnsToTransfer _
Order By column.DisplayIndex _
Select column.Index).ToList()
Dim columnCompany As Integer = indexes(0)
Dim columnEmail As Integer = indexes(1)
Dim columnFirstName As Integer = indexes(2)
Dim columnSurname As Integer = indexes(3)
Dim columnPostCode As Integer = indexes(4)
Dim columnTelephone As Integer = indexes(5)
Dim columnEmployeeBand As Integer = indexes(6)
Dim DeleteConnection As New Data.SqlClient.SqlConnection
DeleteConnection.ConnectionString = "Data Source=DC01\SQLEXPRESS;Initial Catalog=YCM;User ID=sa;Password=S0rtmypc!"
DeleteConnection.Open()
Dim sqlDTM As String = "Delete From TempMapped"
Dim command As New SqlCommand(sqlDTM, DeleteConnection)
command.ExecuteNonQuery()
Dim sqlDTSR As String = "Delete From TempSplitReq"
command = New SqlCommand(sqlDTSR, DeleteConnection)
command.ExecuteNonQuery()
DeleteConnection.Close()
If chkContactSplitReq.Checked = True Then
Dim dt As New DataTable()
Using con As New OleDbConnection(conString)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
cmd.CommandText = (Convert.ToString("SELECT * From [") & excelSheet) & "] Order By" & columnCompany & "OFFSET 0 ROWS FETCH NEXT 100000 ROWS ONLY ""
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
End Using
End Using
End Using
Dim connection As String = "Data Source=DC01\SQLEXPRESS;Initial Catalog=YCM;User ID=sa;Password=S0rtmypc!"
Using cn As New SqlConnection(connection)
cn.Open()
Using copy As New SqlBulkCopy(cn)
copy.ColumnMappings.Add(columnCompany, 0)
copy.ColumnMappings.Add(columnEmail, 1)
copy.ColumnMappings.Add(columnFirstName, 2)
copy.ColumnMappings.Add(columnPostCode, 3)
copy.ColumnMappings.Add(columnTelephone, 4)
copy.DestinationTableName = "TempSplitReq"
copy.WriteToServer(dt)
End Using
End Using
Dim SplitConnection As New Data.SqlClient.SqlConnection
SplitConnection.ConnectionString = "Data Source=DC01\SQLEXPRESS;Initial Catalog=YCM;User ID=sa;Password=S0rtmypc!"
SplitConnection.Open()
Dim sqlSplit As String = "TempSplitReq_SaveToMapped"
Dim commandSplit As New SqlCommand(sqlSplit, SplitConnection)
commandSplit.ExecuteNonQuery()
SplitConnection.Close()
Else
Dim dt As New DataTable()
Using con As New OleDbConnection(conString)
Using cmd As New OleDbCommand()
Using oda As New OleDbDataAdapter()
cmd.CommandText = (Convert.ToString("SELECT * From [") & excelSheet) + "] "
cmd.Connection = con
con.Open()
oda.SelectCommand = cmd
oda.Fill(dt)
con.Close()
End Using
End Using
End Using
Dim connection As String = "Data Source=DC01\SQLEXPRESS;Initial Catalog=YCM;User ID=sa;Password=S0rtmypc!"
Using cn As New SqlConnection(connection)
cn.Open()
Using copy As New SqlBulkCopy(cn)
copy.ColumnMappings.Add(columnCompany, 0)
copy.ColumnMappings.Add(columnEmail, 1)
copy.ColumnMappings.Add(columnFirstName, 2)
copy.ColumnMappings.Add(columnSurname, 3)
copy.ColumnMappings.Add(columnPostCode, 4)
copy.ColumnMappings.Add(columnTelephone, 5)
copy.DestinationTableName = "TempMapped"
copy.WriteToServer(dt)
End Using
End Using
End If
MsgBox("Data Mapping Complete")
End Sub
A SqlBulkCopy object has a BatchSize property. I have a similar situation and set
copy.BatchSize = 1000
And mine works with a large spreadsheet import. Adjust this property in your environment for better performance.

How to get last auto increment value in a table? VB.NET

How would you get the last Primary Key/Auto Increment value in a table using OleDb?
I need to get this value so I can create a folder for a record before it is added so that files can be copied to the folder when it is added.
Any idea?
I have tried as following.
##Identity 'Need to insert a record first and I can't do that without copying the files first
SELECT SCOPE_IDENTITY() 'Doesn't work with OleDb
This is the error message I get:
I think this might work:
SELECT MAX(ID) FROM MyTable
you can do it like this because of The Jet 4.0 provider supports ##Identity,
Reference
Dim query As String = "Insert Into Categories (CategoryName) Values (?)"
Dim query2 As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", Category.Text)
conn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = query2
ID = cmd.ExecuteScalar()
End Using
End Using
Try this
Select IDENT_CURRENT('TableName')
It Will retrun Last ID(If it's Auto increment) of your Table
reference
**c#**
string query = "Insert Into Categories (CategoryName) Values (?)";
string query2 = "Select ##Identity";
int ID;
string connect = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb";
using (OleDbConnection conn = new OleDbConnection(connect))
{
using (OleDbCommand cmd = new OleDbCommand(query, conn))
{
cmd.Parameters.AddWithValue("", Category.Text);
conn.Open();
cmd.ExecuteNonQuery();
cmd.CommandText = query2;
ID = (int)cmd.ExecuteScalar();
}
}
**VB**
Dim query As String = "Insert Into Categories (CategoryName) Values (?)"
Dim query2 As String = "Select ##Identity"
Dim ID As Integer
Dim connect As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Northwind.mdb"
Using conn As New OleDbConnection(connect)
Using cmd As New OleDbCommand(query, conn)
cmd.Parameters.AddWithValue("", Category.Text)
conn.Open()
cmd.ExecuteNonQuery()
cmd.CommandText = query2
ID = cmd.ExecuteScalar()
End Using
End Using
refer
You can try Check if NULL first :
Select if(IsNull(Max(ColName)),1,Max(ColName) + 1 ) From YourTable
try this (vb.net)
'''
Dim lastrecord As Integer
Dim command As New SqlCommand("Select IDENT_CURRENT('tbluom')+1", conn)
command.ExecuteNonQuery()
Dim dt As New DataTable()
Dim da As New SqlDataAdapter(command)
lastrecord = command.ExecuteScalar()
txt_uomid.Text = lastrecord
MsgBox(lastrecord)
Dim encode As String = txt_uomid.Text '"99999"
Dim encint As Integer = Integer.Parse(encode) '+ 1
encode = "00" & "-" & encint.ToString("00000").Substring(1, 4)
MsgBox(encode)
''''

Load SQL Statement for Dataset From SqlServer

I have a code that will fill the dataset for my crystal report which was written down as follows:
Dim str1 As String = "SELECT * FROM farm_loan WHERE id = '" & txtAgreement.Text & "'"
Dim str2 As String = "SELECT * FROM cd_farmers WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str3 As String = "SELECT * FROM cd_Address WHERE Customer_ID = '" & txtCustID.Text & "'"
Dim str4 As String = "SELECT * FROM cd_loan_charges WHERE loanid = '" & txtAgreement.Text & "'"
Dim ad1 As SqlDataAdapter = New SqlDataAdapter(str1, Conn)
Dim ad2 As SqlDataAdapter = New SqlDataAdapter(str2, Conn)
Dim ad3 As SqlDataAdapter = New SqlDataAdapter(str3, Conn)
Dim ad4 As SqlDataAdapter = New SqlDataAdapter(str4, Conn)
Dim LDPSDataSet As DataSet = New DataSet()
ad1.Fill(LDPSDataSet, "farm_loan")
ad2.Fill(LDPSDataSet, "cd_farmers")
ad3.Fill(LDPSDataSet, "cd_Address")
ad4.Fill(LDPSDataSet, "cd_loan_charges")
The above code works fine. What I am trying to do is to store the sql statement in one table called tblDataSet and load the same from sql server. Here are my code.
cmd = New SqlCommand("SELECT * FROM tblDataSet WHERE Flag = 'Y'", Conn)
Dim reader As SqlDataReader = cmd.ExecuteReader()
Dim ad As SqlDataAdapter
If reader.HasRows Then
Do While reader.Read()
MySql = reader(1).ToString
Dim table As String = reader(2).ToString
Dim comm As SqlCommand = New SqlCommand(MySql)
comm.Connection = Conn
comm.CommandType = CommandType.Text
comm.Parameters.Add("#AgreementID", SqlDbType.Int).Value=txtAgreement.Text
comm.Parameters.Add("#CustomerID", SqlDbType.Int).Value = txtCustID.Text
Dim ad As SqlDataAdapter = New SqlDataAdapter
For Each tbl As DataTable In LDPSDataSet.Tables()
If tbl.TableName = table Then
ad.SelectCommand = comm
End If
Exit For
ad.Update(tbl)
Next
Loop
End If
I have not encountered any error but no value is fetch to the crystal report.
My code in to fetch data to crystal report is show below.
With mReport
repOptions = .PrintOptions
With repOptions
.PaperOrientation = rptOrientation
.PaperSize = rptSize
.PrinterName = printer
End With
.Load(rptPath, OpenReportMethod.OpenReportByDefault)
.SetDataSource(LDPSDataSet)
'.Refresh()
.PrintToPrinter(1, True, 0, 0)
End With
Please help me identify the problem with my code.
Thanks in advance.