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
Related
In the Database, I used an assigned ProgName = varchar,MaleCuteOff = int,FemaleCutOff=int, and I'm trying to collect User input for the values, but I'm getting an Error
Conversion from string "INSERT INTO CutOff_Point((ProgN" to type
integer is not valid.
Sub save()
Dim query As String = "INSERT INTO CutOff_Point (ProgName, MaleCutOff, FemaleCutOff) VALUES (#colProg, #colMale, #colFemale)"
Using con As New SqlConnection("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True")
Using com As New SqlCommand()
With com
.Connection = con
.CommandType = query
.Parameters.AddWithValue("#colProg", cmbProg.SelectedItem.ToString)
.Parameters.AddWithValue("#colMale", txtMaleCut.Text.ToString)
.Parameters.AddWithValue("#colFemale", txtFemaleCut.Text.ToString)
End With
Try
con.Open()
com.ExecuteNonQuery()
Catch ex As SqlException
MessageBox.Show(ex.Message.ToString(), "Saving data Not Complete")
End Try
End Using
End Using
End Sub
This:
.CommandType = query
should be setting Commandtext, not CommandType. Why set those properties like that in the first place, when you can use the constructor?
Using com As New SqlCommand(query, con)
I am a beginner and really need help. I want to display data from the database and assign the values to the textboxes and a combobox on a form, but I get this error
Incorrect syntax near "="
It appears is on this line
myreader = cmd.ExecuteReader
Please - any help?
Sub ref()
Dim conn As New SqlConnection
conn.ConnectionString = ("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True")
conn.Open()
Dim strsql As String
strsql = "SELECT ProgName,MaleCuteOff,FemaleCutOff from CutOff_Point where ProgName=" + cmbCourse.SelectedItem + ""
Dim cmd As New SqlCommand(strsql, conn)
Dim myreader As SqlDataReader
myreader = cmd.ExecuteReader
myreader.Read()
txtFemale.Text = myreader("FemaleCutOff")
txtMale.Text = myreader("MaleCuteOff")
conn.Close()
End Sub
You should always use SQL parameters to pass parameters to SQL - it avoids embarrasing problems like single quotes breaking the query and deliberate SQL injection attacks.
It's probably best to make sure that there is a selected value before trying to use it.
Some things, e.g. database connections, use "unmanaged resources" and it is necessary to use the Dispose() method to make sure that things are cleaned up afterwards. The Using statement is a convenient way to get the computer to take care of that for you.
I didn't see a need for the query to return the value that was passed to it (ProgName).
You will need to adjust the .SqlDbType and .Size to match the database column.
Option Strict On
' ... other code
Sub Ref()
If cmbCourse.SelectedIndex >= 0 Then
Dim sql As String = "SELECT MaleCuteOff, FemaleCutOff FROM CutOff_Point WHERE ProgName = #ProgName"
Dim connStr = "Data Source=.\;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True"
Using conn As New SqlConnection(connStr),
cmd As New SqlCommand(sql, conn)
cmd.Parameters.Add(New SqlParameter With {.ParameterName = "#ProgName", .SqlDbType = SqlDbType.VarChar, .Size = 99, .Value = cmbCourse.SelectedItem})
conn.Open()
Dim rdr As SqlDataReader = cmd.ExecuteReader()
If rdr.HasRows Then
rdr.Read()
txtFemale.Text = rdr.GetInt32(0).ToString()
txtMale.Text = rdr.GetInt32(1).ToString()
End If
End Using
End If
End Sub
P.S. Shouldn't UEW_ADMISSION_CHEAKER be UEW_ADMISSION_CHECKER? It's best to have things spelt correctly as it is easier to type them.
First of all this Block of Code is not OK. You could use :
Using....End Using Method.
SqlCommand.Parameters Property for security issues.
Connection Strings and Configuration Files for security issues.
Allow me to rewrite your Code using the above methods.
Private Sub RetrieveAndDisplayCutOff()
Dim sbMale As New StringBuilder
Dim sbFemale As New StringBuilder
Dim strsql As String =
"SELECT MaleCutOff,FemaleCutOff FROM CutOff_Point WHERE ProgName = #ComboItem"
Using conn As New SqlConnection("Data Source=.;Initial Catalog=UEW_ADMISSION_CHEAKER;Integrated Security=True"),
CMD As New SqlCommand(strsql, conn)
CMD.Parameters.Add("#ComboItem", SqlDbType.VarChar).Value = ComboBox1.SelectedItem.ToString
conn.Open()
Using MyReader As SqlDataReader = CMD.ExecuteReader
While MyReader.Read 'Returns False if no more rows
'OP mentioned in comments that these fields were int
sbMale.AppendLine(MyReader.GetInt32(0).ToString)
sbFemale.AppendLine(MyReader.GetInt32(1).ToString)
End While
End Using
End Using
txtMale.Text = sbMale.ToString
txtFemale.Text = sbFemale.ToString
End Sub
This is how I set up my command. It stops with the first parameter, UpdateType. This code is being updated from VB.NET 2008 version.
Dim db As New DB()
Dim cmd As SqlCommand = New SqlCommand()
'Put into an object, and use AddWithValue due to Parameters.Add being deprecated.
Dim UpdateType As String = "PARAMETERS"
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.AddWithValue("#UpdateType", SqlDbType.NVarChar).Value = UpdateType
cmd.Parameters.AddWithValue("#OrigJobName", OrigJobName.ToString)
End If
cmd.Parameters.AddWithValue("#UserID", CInt(Utils.GetLoggedInUserID))
cmd.Parameters.AddWithValue("#ProjectName", ProjectName.ToString)
You should use .Add instead with the type and for NVARCHAR, VARCHAR, or VARBINARY
with the length. Here I show how to do the tings you have in the question, I made up lengths just for the example. Using AddWithValue can have negative impact on SQL performance and other things.
Some information to help you can be found in many places including here https://learn.microsoft.com/en-us/dotnet/framework/data/adonet/configuring-parameters-and-parameter-data-types
Dim db As New DB()
Dim cmd As SqlCommand = New SqlCommand()
Dim UpdateType As String = "PARAMETERS"
cmd.CommandType = CommandType.StoredProcedure
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.Add("#UpdateType", SqlDbType.NVarChar, 10).Value = UpdateType
cmd.Parameters.Add("#OrigJobName", SqlDbType.NVarChar, 50).Value = OrigJobName.ToString
End If
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = CInt(Utils.GetLoggedInUserID)
cmd.Parameters.Add("#ProjectName", SqlDbType.NVarChar, 30).Value = ProjectName.ToString
Keep your database objects local to the method where they are used so you can control that they are closed and disposed. `Using...End Using blocks take care of this for you. Note a single Using block is handling both the connection and the command.
The .Add method is NOT being deprecated. What is obsolute is the .Add(String, Object) overload. `.AddWithValue is certainly out of favor. See http://www.dbdelta.com/addwithvalue-is-evil/
and
https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/
and another one:
https://dba.stackexchange.com/questions/195937/addwithvalue-performance-and-plan-cache-implications
Here is another
https://andrevdm.blogspot.com/2010/12/parameterised-queriesdont-use.html
I had to guess at the datatype and column size of your parameters. Check your database for the actual values and correct the code accordingly.
Private Sub OpCode()
Dim UpdateType As String = "PARAMETERS"
Using cn As New SqlConnection("Your connection string"),
cmd As New SqlCommand()
cmd.Connection = cn
If IsNewJob Then
cmd.CommandText = "sp_MB_AddJob"
Else
cmd.CommandText = "sp_MB_UpdateJob"
cmd.Parameters.Add("#UpdateType", SqlDbType.NVarChar, 50).Value = UpdateType
cmd.Parameters.Add("#OrigJobName", SqlDbType.NVarChar, 200).Value = OrigJobName.ToString
End If
cmd.Parameters.Add("#UserID", SqlDbType.Int).Value = CInt(Utils.GetLoggedInUserID)
cmd.Parameters.Add("#ProjectName", SqlDbType.NVarChar, 200).Value = ProjectName.ToString
cn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub
I am trying to insert data from Xml file using a stored procedure, stored procedure as below :
CREATE PROCEDURE xmlreadtest
#xmldoc xml
AS
BEGIN
INSERT INTO Page (KeyId)
SELECT [Key].value('#Id[1]', 'VARCHAR (100)')
FROM #xmldoc.nodes('//Page/Key') AS TEMPTABLE([Key])
END
And Visual Basic calling the procedure :
Function ModfiyData()
Dim xmldocM As New XmlDocument
xmldocM.Load("C:\20170326.66.xml")
Dim SQLComm As New SqlCommand
Dim dbconn As New SqlConnection(con)
dbconn.Open()
SQLComm.Connection = dbconn
SQLComm.CommandText = "xmlreadtest"
SQLComm.CommandType = CommandType.StoredProcedure
SQLComm.Parameters.AddWithValue("#xmldoc", xmldocM)
SQLComm.ExecuteNonQuery()
dbconn.Close()
End Function
When i run the application it give error:
No mapping exists from object type System.Xml.XmlDocument to a known managed provider native type.
Any idea how can i solve this issue..
i am using vb 2015 and sql database file.
Try Casting XmlDocument to SqlXML
Dim xmldocM As New XmlDocument
xmldocM.Load("C:\20170326.66.xml")
Dim sw as new StringWriter()
Dim xw as new XmlTextWriter(sw)
xmldocM.WriteTo(xw)
Dim transactionXml as new StringReader(sw.ToString())
Dim xmlReader AS new XmlTextReader(transactionXml)
Dim XmlParamValue as new SqlXml(xmlReader)
Dim SQLComm As New SqlCommand
Dim dbconn As New SqlConnection(con)
dbconn.Open()
SQLComm.Connection = dbconn
SQLComm.CommandText = "xmlreadtest"
SQLComm.CommandType = CommandType.StoredProcedure
SQLComm.Parameters.AddWithValue("#xmldoc", XmlParamValue )
SQLComm.ExecuteNonQuery()
dbconn.Close()
Every time I tried to connect to the database it give me this error "The ConnectionString property has not been initialized"
what can I do to solve this?
here are my codes
Module Module1
Function GetInfoForStudent(ByRef QueryName As String, ByVal UserName As String, ByVal Password As String) As DataTable
Using Con As New SqlConnection
Try
Using OleCon As New SqlConnection
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library
Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Con.Open()
Dim Cmd As SqlCommand = Con.CreateCommand()
Cmd.CommandType = CommandType.StoredProcedure
Cmd.CommandText = QueryName
Cmd.Parameters.AddWithValue("#user", UserName)
Cmd.Parameters.AddWithValue("#pass", Password)
Dim da As New SqlDataAdapter(Cmd)
Dim ds As New DataTable()
da.Fill(ds)
Return ds
End Using
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
End Using
End Function
End Module
Sub ShowStudentInfo()
Dim dt As DataTable = GetInfoForStudent("MyStoredProcName", "#user", "#pass")
' Since (presumably) only one is returned
With dt.Rows(0)
' Assign your text boxes
StudentIDTextBox.Text = .Item("StudentID")
LoginIDTextBox.Text = .Item("LoginID")
Student_NameTextBox.Text = .Item("Student Name")
Student_addressTextBox.Text = .Item("Student address")
End With
End Sub
You never assigned your connection string to the connection object, just like the error is saying.
Insert a line setting the connection string before con.open.
Con.connectionstring = connection
Con.Open()
Or better yet, change your using statement as follows
Dim Connection As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=G:\VB Project\Library Catalog System\Library Catalog System\library.mdf;Integrated
Security=True;Connect Timeout=30;User Instance=True"
Using Con As New SqlConnection(connection)
You are creating the connection string object but never assigning it to your SqlCommand object.