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
Related
I have a problem with search: how do I search our language text from SQL query and which type data I select
Dim cmd As New SqlCommand
cmd.Connection = cn
cmd.CommandText = "SELECT * FROM Table_12 WHERE m='" & "دولت خان" & "'"
Dim adapter As New SqlDataAdapter(cmd)
Dim table As New DataTable()
adapter.Fill(table)
If table.Rows.Count() > 0 Then
TextBox2.Text = table.Rows(0)(1).ToString()
MessageBox.Show("Record found!")
Else
MessageBox.Show("Record not found!")
Keep your database objects local so you can control that they are closed and disposed. A single Using...End Using block handles this for you.
You can pass your connection string directly to the constructor of the connection and pass the command text and connection directly to the constructor of the command.
Always use parameters to avoid Sql Injection. The value concatenated to an sql command string is potentially executable. Parameter values are not.
Private Sub OpCode()
Dim dt As New DataTable
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand("SELECT * FROM Table_12 WHERE m= #m;", cn)
cmd.Parameters.Add("#m", SqlDbType.NVarChar, 50).Value = "دولت خان"
cn.Open()
dt.Load(cmd.ExecuteReader)
End Using
If dt.Rows.Count() > 0 Then
TextBox2.Text = dt.Rows(0)(1).ToString()
MessageBox.Show("Record found!")
Else
MessageBox.Show("Record not found!")
End If
End Sub
Search with like clause for unicode in column m and show column o:
cmd.CommandText = "SELECT o FROM Table_12 WHERE m like N'%" & "دولت خان" & "%'"
Currently trying to update an SQL Server database from an Access db, it works importing new records but fails on when I reimport the file and there is a duplicate - in looking for it to insert the row if it's not there (working), but skip if it already exists. The first column has the primary key set.
Dim table As DataTable = New DataTable
Dim accConnection As New OleDb.OleDbConnection(
"Provider=Microsoft.JET.OLEDB.4.0; Data Source='C:\Tester.mdb';User Id=admin; Password=;")
Dim sqlConnection As New SqlClient.SqlConnection(
"Data Source=10.75.24.94;Initial Catalog=CTData;User ID=sql;Password=")
Try
'Import the Access data
accConnection.Open()
Dim accDataAdapter = New OleDb.OleDbDataAdapter(
"SELECT * FROM Import_test", accConnection)
accDataAdapter.Fill(table)
accConnection.Close()
'Export to MS SQL
For Each row As DataRow In table.Rows
row.SetAdded()
Next
sqlConnection.Open()
Dim sqlDataAdapter As New SqlClient.SqlDataAdapter(
"SELECT * FROM Import_test", sqlConnection)
Dim sqlCommandBuilder As New SqlClient.SqlCommandBuilder(sqlDataAdapter)
sqlDataAdapter.InsertCommand = sqlCommandBuilder.GetInsertCommand()
sqlDataAdapter.UpdateCommand = sqlCommandBuilder.GetUpdateCommand()
sqlDataAdapter.DeleteCommand = sqlCommandBuilder.GetDeleteCommand()
sqlDataAdapter.Update(table)
sqlConnection.Close()
Catch ex As Exception
If accConnection.State = ConnectionState.Open Then
accConnection.Close()
End If
If sqlConnection.State = ConnectionState.Open Then
sqlConnection.Close()
End If
MessageBox.Show("Import failed with error: " &
Environment.NewLine & Environment.NewLine &
ex.ToString)
End Try
The error I'm presented with is:
Violation of Primary key. Cannot insert duplicate key in object.
I think you can remove VB from the equation (I like to make things as simple as possible, without over-simplifying it). You have several options available.
INSERT INTO Table
SELECT * FROM #Table xx
WHERE NOT EXISTS (SELECT 1 FROM Table rs WHERE rs.id = xx.id)
Or . . .
DELETE FROM Table
WHERE (ID NOT IN (SELECT MAX(ID) AS Expr1
FROM Table
AS Table_1 GROUP BY NAME,ADDRESS,CITY,STATE,ZIP,PHONE,ETC.))
There are a lot of other ways to handle this as well. Is you need to incorporate VB, you can do something like this.
Dim cmd As New OleDbCommand
Dim con As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\your_path\DB.accdb")
Dim queryResult As Integer
Dim sqlQRY As String = "SELECT COUNT(*) AS FROM ESRRegister WHERE ID = '" & IDtxt.Text & "'"
con.Open()
cmd.Connection = con
cmd.CommandType = CommandType.Text
If queryResult > 0 Then
cmd.CommandText = "insert into ESRRegister (Dt,ID)VALUES ('" & Dttxt.Text & "' , '" & IDtxt.Text & "')"
queryResult = cmd.ExecuteScalar()
MsgBox("Added Successfuly")
Else
MessageBox.Show("Already Exists!", "ALI ENTERPRISES", MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
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
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.
I am currently using HDI Membership provider and the design looks as shown below:
Now I am trying to create a new user and insert those values into the database as shown below:
Try
Dim connectionString As String = "Data Source=.\sqlexpress;Initial Catalog=HDIMembershipProvider;Integrated Security=True"
Using cn As New SqlConnection(connectionString)
cn.Open()
Dim cmd As New SqlCommand()
cmd.CommandText = "INSERT INTO Users VALUES(#Username,#Password,#Email,#PasswordQuestion,#PasswordAnswer)"
Dim param1 As New SqlParameter()
param1.ParameterName = "#Username"
param1.Value = txtUsername.Text.Trim()
cmd.Parameters.Add(param1)
Dim param2 As New SqlParameter()
param2.ParameterName = "#Password"
param2.Value = txtPassword.Text.Trim()
cmd.Parameters.Add(param2)
Dim param3 As New SqlParameter()
param3.ParameterName = "#Email"
param3.Value = txtEmail.Text.Trim()
cmd.Parameters.Add(param3)
Dim param4 As New SqlParameter()
param4.ParameterName = "#PasswordQuestion"
param4.Value = txtSecurityQuestion.Text.Trim()
cmd.Parameters.Add(param4)
Dim param5 As New SqlParameter()
param5.ParameterName = "#PasswordAnswer"
param5.Value = txtSecurityAnswer.Text.Trim()
cmd.Parameters.Add(param5)
cmd.Connection = cn
cmd.ExecuteNonQuery()
cn.Close()
End Using
Successlbl.show
Successlbl.show.Text = "Regisration Success."
Catch
Errolbl.Show()
Errolbl.Text = "Your account was not created.Please try again."
End Try
Now the problem is the data is not inserting to the database. I would like to know If anyone can point me where I'm going wrong?
Your insert statement is incorrect - since you are not specifying any field names you should be supplying values for all columns.
The fix is to supply the names of the columns you are insert into.
The screenshot also shows that there is a required ApplicationName column, so unless it has a DEFAULT defined, you will need to supply that as well.
Assuming you have a DEFAULT defined on ApplicationName:
cmd.CommandText = "INSERT INTO Users ( Username, Password, Email, PasswordQuestion, PasswordAnswer) VALUES(#Username,#Password,#Email,#PasswordQuestion,#PasswordAnswer)"