loading xml file to stored procedure - sql-server

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()

Related

How to Parameterized Queries with the SqlDataSource (VB)

This is my code example to run parameterized query in VB.NET:
Dim sqlconn As New SqlConnection(connectionString)
sqlconn.Open()
Dim cmd As New SqlCommand
cmd.CommandText = "Select * from TAble1 Where SkuCode in (#SKU)"
cmd.Connection = sqlconn
Dim parm As New SqlParameter
parm.Value ="1" 'This is working
parm.ParameterName = "#SKU"
cmd.Parameters.Add(parm)
Dim ds As New DataSet
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(ds)
Dim dt As DataTable
dt = ds.Tables(0)
If dt.Rows.Count > 0 Then
MsgBox("Done")
Else
MsgBox("Not done.")
End If
If I run this example in VB.NET this returns the result successfully.
But there is an issue while trying to get results with multiple in records... this is not working.
Please check and suggest the change we have to do to run in query with parameters.
'parm.Value = "N'1', N'2'" 'this does not work.
'parm.Value = "'1','2'" 'this does not work.
I have tried these parameter value but it does not work.
SQL parameters are scalar and only accept a single value. You can use the sqldbtype.Structured though it gets a bit complicated.
I've found that if you need to pass in a set of parameters for an IN where the number of parameters is dynamics, the most effective way (unfortunately) is:
String interpolation/concatenation without parameters
Loop to build out the parameters and add them to your sqlcommand
LINQ to build out the parameters and add them to your sqlcommand
I've provided an example of the linq option below.
Dim sqlParams As Dictionary(Of String, Integer) = integers.ToDictionary(Function(i) $"#ParamValue{i}", Function(i) i)
Dim ds As New DataSet
Dim dt As DataTable
Using db as new SqlConnection(conn)
conn.open()
Using cmd As New SqlCommand($"SELECT * FROM Table1 WHERE SkuCode IN (-1, {String.Join(", ", sqlParams.Select(Function(f) f.Key))}", db)
cmd.Parameters.AddRange(sqlParams.Select(Function(f) New SqlParameter(f.Key, SqlDbType.BigInt).Value = f.Value).ToArray())
Dim sqlDa As New SqlDataAdapter(cmd)
sqlDa.Fill(ds)
dt = ds.Tables(0)
End Using
End Using
MsgBox(If(dt.Rows.Count > 0, "Done", "Not done"))

Getting data from a stored procedure

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

SQL Server cursor to vb.net

everyone, How can I read a cursor from a stored procedure?
This is my code, but it's not working
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conexionBD").ToString())
Public Function LoadData() As String
Dim strQuery As String
strQuery = "Kardex_P''"
Using (con)
Dim sqlComm As SqlCommand = New SqlCommand(strQuery, con)
con.Open()
Dim sqlReader As SqlDataReader = sqlComm.ExecuteReader()
If sqlReader.HasRows Then
While (sqlReader.Read())
txtReporte = sqlReader.ToString
End While
End If
End Using
Return txtReporte
End Function
Please I need your help.
Thanks in advance
The cursor code will live in the stored procedure that ultimately returns a set of rows to read. Reference each column by ordinal value or name:
txtReporte.Text = sqlReader(0).ToString()
or
txtReporte.Text = sqlReader("YourColumnName").ToString()
What is wrong in OP code and how to fix it.
Dim con As New SqlConnection(ConfigurationManager.ConnectionStrings("conexionBD").ConnectionString
''//.ToString()) wrong but not fatal
Public Function LoadData() As String
Dim txtReporte as String = "" ''//you return this so declare
Dim strQuery As String
strQuery = "Kardex_P" ''//"Kardex_P''" This supposed to be SP name. What '' do inside?
Using (con) ''//this is good
Dim sqlComm As SqlCommand = New SqlCommand(strQuery, con)
''//By default command type is text so next line is critical
sqlComm.CommandType = CommandType.StoredProcedure
con.Open()
Dim sqlReader As SqlDataReader = sqlComm.ExecuteReader()
''//If sqlReader.HasRows Then checking "HasRows is redundant here
While (sqlReader.Read())
''//txtReporte = sqlReader.ToString no comment
txtReporte &= sqlReader("SomeField")
End While
''//End If
con.Close() ''//cleanup recommended
End Using
Return txtReporte
End Function
I hope this will work. Not perfect of course.

Populating ListBox using parameterized query on VB.Net

I have the following code that involves populating a ListBox. How can I parameterize the query to prevent SQL injection?
sqlCon = New SqlConnection(strConn)
sqlCon.Open()
Dim sql As String = "SELECT * FROM employees where id = & textbox1.text &"
Dim adapter As New SqlDataAdapter(sql, sqlCon)
Dim da As New DataTable
adapter.Fill(da)
ListBox1.DisplayMember = "employees"
ListBox1.DataSource = da
ListBox1.ValueMember = "employees"
sqlCon.Close()
Maybe this will help:
Using sqlCon As SqlConnection = New SqlConnection(strConn)
sqlCon.Open()
Dim sql As String = "SELECT * FROM employees WHERE id = #id"
Dim adapter As SqlDataAdapter = New SqlDataAdapter(sql, sqlCon)
adapter.SelectCommand.Parameters.Add(New SqlParameter("#id", textbox1.Text))
Dim da As New DataTable
adapter.Fill(da)
ListBox1.DisplayMember = "employees"
ListBox1.DataSource = da
ListBox1.ValueMember = "employees"
End Using
It's better to enclose the code inside the Using so that the SqlConnection will be disposed even an exception is thrown. Also instead of using SELECT *, you may want to specify the column names.

"The ConnectionString property has not been initialized" error in VB.NET

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.

Resources