How would I create a query that returns a column in the database? The SQL select statement is easy. I'm having issues with the VB side.
SELECT UserNO
FROM UserTable
WHERE UserID = user;
I need to then get that UserNO and pass it to another T-SQL stored procedure. How would I go about running a SELECT query and getting the results back in Visual Basic?
Attached is some of my code. The code below adds the user to the DB however the UserNo (INTEGER) is automatically generated by SQL Server as the INSERT statement is run in the insert stored procedure, so I need to pull the UserNO after the user is created.
Public conwd As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Public conwp As SqlConnection = New SqlConnection("Server=*****;Database=*****;User Id=****;Password=****")
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwp)
Dim cmdD As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'", conwd)
conmp.Open()
conmd.Open()
cmdP.ExecuteNonQuery()
cmdD.ExecuteNonQuery()
The Using..End Using blocks close and dispose of your data objects that might contain unmanaged code. The Parameters help prevent SQL injection.
Private Sub OPCode2()
Dim newID As Integer
Dim sql = "Insert Into UserTable (User) Values (#User); Select SCOPE_IDENTITY();"
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.Parameters.Add("#User", SqlDbType.NVarChar).Value = "Brian Weaver"
cn.Open()
newID = CInt(cmd.ExecuteScalar)
End Using
End Using
'Use the newID in your next command
UserStoredProcedure(newID)
End Sub
Private Sub UseStoredProcedure(id As Integer)
Dim sql = "InsertSomeUserInfo" 'the name of your stored procedure
Using cn As New SqlConnection("Your Connection String")
Using cmd As New SqlCommand(sql, cn)
cmd.CommandType = CommandType.StoredProcedure
'whatever parameter names and types your stored procedure uses
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = id
cmd.Parameters.Add("#Salary", SqlDbType.Decimal).Value = 50000
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Dim cmdP As SqlCommand = New SqlCommand("EXECUTE [dbo].[AddNewUserWestonTemp] '" + user + "'" + "; SELECT CAST(scope_identity() AS int", conwp)
Dim userNo as Integer = cmdP.ExecuteScalar()
ExecuteScalar retrieves the first line of the result
I have a stored procedure like this:
Select name, surname from student
and I can't get data with VB.Net.
My code is:
Dim reader As SqlDataReader
With dbCmd
.CommandType = CommandType.StoredProcedure
.CommandText = "sp_myPersonalSP"
End With
reader = dbCmd.ExecuteReader()
But Visual Studio send me an exception when it try "reader = dbCmd.ExecuteReader()":
Procedure sp_myPersonalSP has no parameters and arguments were supplied.
Thanks! I am a newbie in VB.Net :-(
A function that returns a datatable from Sql Server executing a stored procedure:
Public Function GetApplicationType() As DataTable
Dim MyDataTable As DataTable = New DataTable()
' The connection string information is in the web.config file - see below
Dim con = ConfigurationManager.ConnectionStrings("MyConnectionString").ToString()
Dim MyDataAdapter As SqlDataAdapter = New SqlDataAdapter("GetSomeData", con)
MyDataAdapter.SelectCommand.CommandType = CommandType.StoredProcedure
' add the parameters in the same order and type as what the stored procedure expects, they must match the names in the stored procedure and are case sensitive.
MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("#ParameterName", SqlDbType.VarChar, 10));
MyDataAdapter.SelectCommand.Parameters.Add(new SqlParameter("#Parametername2", SqlDbType.VarChar, 40));
MyDataAdapter.SelectCommand.Parameters["#ParameterName"].Value = somedata1;
MyDataAdapter.SelectCommand.Parameters["#ParameterName2"].Value = somedata2;
MyDataAdapter.Fill(MyDataTable)
Return MyDataTable
End Function
web.config
<connectionStrings>
<add name="MyConnectionString" connectionString="server=192.168.11.11;database=Test;uid=someusername; pwd=somepassword" providerName="System.Data.SqlClient" />
</connectionStrings>
You can display your query results in a DataGridView. You need to have a connection for the command to execute. Open the connection before you execute the command. The Using...End Using statements with ensure that your objects are closed and disposed event if there is an error.
Private Sub GetData()
Using cn As New SqlConnection("Your Connection String")
Using dbCmd As New SqlCommand
With dbCmd
.CommandType = CommandType.StoredProcedure
.CommandText = "sp_myPersonalSP"
.Connection = cn
End With
cn.Open()
Using reader As SqlDataReader = dbCmd.ExecuteReader()
'You can view the result of your query in a DataGridView
Dim dt As New DataTable
dt.Load(reader)
DataGridView1.DataSource = dt
End Using
End Using
End Using
End Sub
to retrieve data from stored procedure, just call your stored procedure name like this.
Dim stringquery = "CALL YOURSTOREDPROCNAME()"
Try my Code:
Dim dt as new Datatable
con.Open()
Dim query = "Call StoredProcedureName()"
command = New SqlCommand(query, con)
adapter.SelectCommand = command
dt.Clear()
adapter.Fill(dt)
con.Close()
-KEVIN
I have a generic update function that takes a datatable, select query and uses this to update the database tables.It is working fine. I need to know is there a way to get back the inserted row's ID (identity field) by changing something in the below code.
Public Function UpdateDataTable_GetID(ByVal dt As DataTable, ByVal SQL As String, ByVal connString As String) As Integer
Dim conn As SqlConnection = Nothing
Dim cmd As SqlCommand
Dim adp As SqlDataAdapter = Nothing
Dim cmdBuilder As SqlCommandBuilder = Nothing
Dim UpdatedID As Integer
If SQL.Length <= 0 Then
Return False
End If
conn = New Data.SqlClient.SqlConnection(connString)
cmd = New Data.SqlClient.SqlCommand
cmd.Connection = conn
cmd.CommandText = SQL
cmd.CommandType = CommandType.Text
adp = New Data.SqlClient.SqlDataAdapter(cmd)
cmdBuilder = New Data.SqlClient.SqlCommandBuilder(adp)
Try
UpdatedID = Convert.ToInt32(adp.Update(dt)) ' What to do here to get the just inserted ID instead of number of records updated
adp.Dispose()
cmdBuilder.Dispose()
Return UpdatedID
Catch ex As System.Data.SqlClient.SqlException
' Closing connection
Return -1
Finally
End try
End function
I am aware of solutions wherein I can append "select scope_identity()" to the insert Command of data adapter's query using designer as well as editing the adapter's insertcommand text and then doing an ExecuteScalar(). I want to know if the generic adapter.Update() can be tweaked to get the inserted row's ID.
you can subscribe to this event in code like this : (C# I dont know VB)
adp.RowUpdated += adapter_RowUpdated;
and write the event yourself :
void adapter_RowUpdated(object sender, SqlRowUpdatedEventArgs e)
{
if (e.StatementType == StatementType.Insert)
{
object id = e.Command.Parameters["#ID"].Value;
e.Row[_identityFieldName] = id;
}
}
In this example the following has been added to the commandtext first :
SET #ID = SCOPE_IDENTITY()
and a private variable _identityFieldName has been filled.
Maybe this can help you.
EDIT: I noticed you also use an SqlCommandBuilder that makes things easier to add the Scope identity :
SqlCommand inserter = new SqlCommand();
inserter = cmdBuilder.GetInsertCommand(true).Clone();
inserter.CommandText += " SET #ID = SCOPE_IDENTITY()";
SqlParameter param = new SqlParameter();
param.Direction = ParameterDirection.Output;
param.Size = 4;
param.DbType = DbType.Int32;
param.ParameterName = "#ID";
inserter.Parameters.Add(param);
adp.InsertCommand = inserter;
The following stored procedure works as I want in the Visual Studio designer. The result is a table containing all the race distances for the input #CourseName
ALTER PROCEDURE [dbo].[getCourseDistancesProc]
#CourseName nvarchar(50)
AS
BEGIN
SET NOCOUNT ON;
SELECT DISTINCT
RaceDistances.RaceDistance
FROM
RacingMaster
JOIN
RaceDistances ON RacingMaster.Dist_Of_Race_FK = RaceDistances.PKRaceDistancesId
JOIN
Courses ON RacingMaster.RM_Course_FK = Courses.PKCourseId
WHERE
CourseName = #CourseName
END
I want to call the stored procedure from a vb.net application. What data type do I declare as the output variable so that the full result set is returned to the calling app?
There was obviously more work to be done than I had realized, but just in case anyone else stumbles across this question the solution I finally adapted from elsewhere is:-
Dim myConn As SqlConnection
Dim myCmd As SqlCommand
Dim results As String
Dim ConnectionString As String
' Create the connection string.
ConnectionString = "Data Source=*********;" & _
"Initial Catalog=*******;" & _
"Integrated Security=SSPI;"
myConn = New SqlConnection(ConnectionString)
myConn.Open()
Dim InputName As String
InputName = TextBox1.Text
myCmd = New SqlCommand()
myCmd.CommandText = "getCourseDistancesProc"
myCmd.CommandType = CommandType.StoredProcedure
myCmd.Parameters.AddWithValue("#CourseName", Odbc.OdbcType.NVarChar).Value = InputName
myCmd.Connection = myConn
Dim myReader As SqlDataReader = myCmd.ExecuteReader()
If myReader.HasRows Then
Do While myReader.Read()
Dim var As String
var = myReader.GetString(0)
MsgBox(var)
Loop
Else
MsgBox("No rows found.")
End If
myReader.Close()
Obviously, the above is just to demonstrate that the requested data is indeed coming back from the database. But now I know that it is I can handle it in a more useful way.
Problem:
I need to dump the contents of my DataGridView into a SQL Server Database Table. I've got the datagridview loading fine, no problems there. I'm just not familiar enough with VB.NET to understand how to get that data into a DB table.
Code: (so far)
Dim connection As New Data.SqlClient.SqlConnection
Dim dataAdapter As New Data.SqlClient.SqlDataAdapter
Dim command As New Data.SqlClient.SqlCommand
Dim dataSet As New Data.DataSet
connection.ConnectionString = "Server= server; Database= DB; integrated security=true"
command.CommandText = "INSERT INTO <table> (Col1, Col2, Col3, Col4) VALUES (#Name, #Property, #Value, #Date)"
dataAdapter.InsertCommand.Parameters.Add("#ServerName", SqlDbType.VarChar)
dataAdapter.InsertCommand.Parameters.Add("#Property", SqlDbType.VarChar)
dataAdapter.InsertCommand.Parameters.Add("#Value", SqlDbType.VarChar)
dataAdapter.InsertCommand.Parameters.Add("#CaptureDate", SqlDbType.DateTime)
For i As Integer = 0 To DataGridView.Rows.Count - 1
dataAdapter.InsertCommand.Parameters(0).Value = dgvServerConfig.Rows(i).Cells(0).Value
dataAdapter.InsertCommand.Parameters(1).Value = dgvServerConfig.Rows(i).Cells(1).Value
dataAdapter.InsertCommand.Parameters(2).Value = dgvServerConfig.Rows(i).Cells(2).Value
dataAdapter.InsertCommand.Parameters(3).Value = dgvServerConfig.Rows(i).Cells(3).Value
Next
connection.Open()
command.Connection = connection
dataAdapter.SelectCommand = command
What am I missing here? Nothing is getting inserted into my table. Any help would be appreciated. Like I said, I'm not very familiar with VB so take it easy on me.
Well, you need to execute the command, not simply add to the DataAdapter
Also, as it coded now, you don't need the DataAdapter at all.
Dim connection As New Data.SqlClient.SqlConnection
Dim command As New Data.SqlClient.SqlCommand
connection.ConnectionString = "Server= server; Database= DB; integrated security=true"
command.CommandText = "INSERT INTO <table> (Col1, Col2, Col3, Col4) VALUES (#Name, #Property, #Value, #Date)"
command.Parameters.Add("#ServerName", SqlDbType.VarChar)
command.Parameters.Add("#Property", SqlDbType.VarChar)
command.Parameters.Add("#Value", SqlDbType.VarChar)
command.Parameters.Add("#CaptureDate", SqlDbType.DateTime)
connection.Open()
command.Connection = connection
For i As Integer = 0 To DataGridView.Rows.Count - 1
command.Parameters(0).Value = dgvServerConfig.Rows(i).Cells(0).Value
command.Parameters(1).Value = dgvServerConfig.Rows(i).Cells(1).Value
command.Parameters(2).Value = dgvServerConfig.Rows(i).Cells(2).Value
command.Parameters(3).Value = dgvServerConfig.Rows(i).Cells(3).Value
command.ExecuteNonQuery()
Next
However this calls the database to insert one row at a time. I think it is better to look at the SqlDataAdapter.Update method that resolves the insert/update work with just one call.
Using the SqlDataAdapter.Update method, requires that you save in a global variable the Adapter used at the moment in which you have filled the DataGridView and add a SqlCommandBuilder that generates for you the InsertCommand, UpdateCommand and DeleteCommand
' At form loading'
Dim adapter As New OleDbDataAdapter()
adapter.SelectCommand = New OleDbCommand("SELECT COL1, COL2,COL3,COL4 FROM TABLE", connection)
Dim builder As OleDbCommandBuilder = New OleDbCommandBuilder(adapter)
connection.Open()
Dim myTable As DataTable = New DataTable
adapter.Fill(myTable)
DataGridView.DataSource = myTable
....
' at grid save'
Dim myTable = CType(DataGridView.DataSource, DataTable)
adapter.Update(myTable)
For each object in your GridView, you need to find it and determine its value. So for example,
DropDownList ddlToLoc = (DropDownList)gvMovesMod.Rows[0].FindControl("ddlToLoc");
Then, determine ddlToLoc's SelectedValue and insert to database
You can call: command.ExecuteNonQuery to insert data to the DB.
More info here
TRY THIS METHOD
For index As Integer = 0 To DataGridView1.RowCount - 1
Dim connectionString = "Data Source=localhost;port=3306;Initial Catalog=hasna;User Id=root;password=''; Convert Zero Datetime=True"
Dim query0 = "insert into itemledgerfinal(Date,BillDate,BillNo,ItemName,GST,Rate,MRP,TotalQty,PurchaseRate,WholesaleRate,Total,Type,OpeningBalance,Purchase,Sale,ClosingBalance,ID) values(#Date,#BillDate,#BillNo,#ItemName,#GST,#Rate,#MRP,#TotalQty,#PurchaseRate,#WholesaleRate,#Total,#Type,#OpeningBalance,#Purchase,#Sale,#ClosingBalance,#ID)"
Dim connection0 As New MySqlConnection(connectionString)
Dim command0 As New MySqlCommand(query0, connection0)
command0.Parameters.AddWithValue("#Date", DataGridView1.Rows(index).Cells(0).Value)
command0.Parameters.AddWithValue("#BillDate", DataGridView1.Rows(index).Cells(1).Value)
command0.Parameters.AddWithValue("#BillNo", DataGridView1.Rows(index).Cells(2).Value)
command0.Parameters.AddWithValue("#ItemName", DataGridView1.Rows(index).Cells(3).Value)
command0.Parameters.AddWithValue("#GST", DataGridView1.Rows(index).Cells(4).Value)
command0.Parameters.AddWithValue("#Rate", DataGridView1.Rows(index).Cells(5).Value)
command0.Parameters.AddWithValue("#MRP", DataGridView1.Rows(index).Cells(6).Value)
command0.Parameters.AddWithValue("#TotalQty", DataGridView1.Rows(index).Cells(7).Value)
command0.Parameters.AddWithValue("#PurchaseRate", DataGridView1.Rows(index).Cells(8).Value)
command0.Parameters.AddWithValue("#WholesaleRate", DataGridView1.Rows(index).Cells(9).Value)
command0.Parameters.AddWithValue("#Total", DataGridView1.Rows(index).Cells(10).Value)
command0.Parameters.AddWithValue("#Type", DataGridView1.Rows(index).Cells(11).Value)
command0.Parameters.AddWithValue("#OpeningBalance", DataGridView1.Rows(index).Cells(12).Value)
command0.Parameters.AddWithValue("#Purchase", DataGridView1.Rows(index).Cells(13).Value)
command0.Parameters.AddWithValue("#Sale", DataGridView1.Rows(index).Cells(14).Value)
command0.Parameters.AddWithValue("#ClosingBalance", DataGridView1.Rows(index).Cells(15).Value)
command0.Parameters.AddWithValue("#ID", DataGridView1.Rows(index).Cells(16).Value)
connection0.Open()
command0.Connection = Connection
command0.ExecuteNonQuery()
Next