ASP.net dataset - asp.net

da = New SqlDataAdapter("select * from revision_cycle_documenttype_mapping where project_id=" & Session("project_id"), con)
cb = New SqlCommandBuilder(da)
ds = New DataSet
da.Fill(ds, "revision_cycle_documenttype_mapping") <<--
mapping_count = ds.Tables("revision_cycle_documenttype_mapping").Rows.Count
Response.Write(mapping_count)
I am getting an error "Incorrect syntax near '=' ".
I have shown on which portion it's throwing error i.e da.fill.
Can you please help me?

EDIT
If it throws error on da.Fill then try to see the resulting SQL code first. Your project_id may be empty.
Edit
This is a possible solution
Dim projectId As Integer
If Session("project_id") IsNot Nothing AndAlso IsNumeric(Session("project_id")) Then
projectId = Session("project_id")
da = New SqlDataAdapter("select * from revision_cycle_documenttype_mapping where project_id=" & projectId, con)
cb = New SqlCommandBuilder(da)
ds = New DataSet
da.Fill(ds, "revision_cycle_documenttype_mapping") <<--
mapping_count = ds.Tables("revision_cycle_documenttype_mapping").Rows.Count
Response.Write(mapping_count)
End If

I think your session Session("project_id") is empty, and this is not the best way to add a parameter in ur sql statement. your code here is vulnerable to sql injections.
you should first check if your session is empty and then you should add parameters by declaring a sqlcommand and assign parameters to it:
dim project_id as integer = 0
If Session("project_id") IsNot Nothing AndAlso IsNumeric(Session("project_id")) Then
project_id = Session("project_id")
end if
dim cmd as new sqlcommand
cmd.parameters.add("#project_id",project_id)
the rest of your code would stay the same

Use Parameters and check the null.
Dim projectid=0
If Not IsNothing(Session("project_id")) Then
projectid=DirectCast(Session("project_id"),Integer)
End If
Dim sql="select * from revision_cycle_documenttype_mapping where project_id=#project_id"
dim cmd as new SqlCommand(sql,con)
cmd.Parameters.AddWithValue("#project_id",projectid)
da = New SqlDataAdapter=(cmd)
cb = New SqlCommandBuilder(da)
ds = New DataSet
da.Fill(ds, "revision_cycle_documenttype_mapping")

Related

Get User Collection Type Object (Table) as Out Parameter from Oracle stored procedure

I need to get back from an Oracle stored procedure (inside a package) an output parameter defined as user collection type object (a table).
Procedure GetCon (DataRif IN VARCHAR2,Results OUT my_collectiontype)
IS
BEGIN
select my_ObjectType(Col1,Col2)
bulk collect into Results
FROM
TABLE(PMS.myfunc(DataRif ,'31-12-2019');
END;
....
The Function PMS.myfunc returns a my_collectiontype object
In my code (Asp.net 4.0 VB.NET with Oracle ManagedDataAccess Drivers), I've tried
strConn = "Data Source=XE.WORK;User Id=PMS;Password=xxxx"
Dim con As New OracleConnection(strConn)
Dim dt As DataTable = New DataTable()
Dim da As OracleDataAdapter = New OracleDataAdapter()
con.Open()
Dim cmd As New OracleCommand()
cmd.Connection = con
cmd.CommandText = "MySchema.MyPackage.GetCon"
cmd.CommandType = CommandType.StoredProcedure
cmd.Parameters.Add("DataRif", OracleDbType.Varchar2,"23-07-2019", ParameterDirection.Input)
cmd.Parameters.Add("Results", OracleDbType.RefCursor).Direction = ParameterDirection.Output
da.SelectCommand = cmd
cmd.ExecuteNonQuery()
da.Fill(dt)
.....
I get this error
ORA-06550: line 1, column 7: PLS-00306: wrong number or types of arguments in call to 'GETCONT'
ORA-06550: line 1, column 7: PL/SQL: Statement ignored"
Sure the out parameter is not a ref cursor but I can't find the right object.
I need to use a stored procedure because I know it's possible execute something like this as simple view
SELECT * FROM TABLE (PMS.myfunc('01-01-2019', '31-12-2019')
but this solution is not the best at the moment.
Thanks in advance.
Solved in this following way that permits to receive a cursor and put it in a dataset.
Create Stored Procedure in Oracle like this
CREATE OR REPLACE PROCEDURE get_emp_rs (p_recordset OUT SYS_REFCURSOR) AS
BEGIN
OPEN p_recordset FOR
SELECT DIP_ID,DIP_NAME
FROM TABLE(fn_GetDataFunction('01-01-2019','31-12-2019','15-09-2019'));
END get_emp_rs;
/
In Asp.net
Public Function TestCursor() As DataSet
Dim strConn As String = "Data Source=MYSOURCE;User Id=MYID;Password=xxxxx"
Dim dsReturn As DataSet = Nothing
Try
Using con As New OracleConnection(strConn)
Using sda As New OracleDataAdapter()
Dim cmd As New OracleCommand()
cmd.Connection = con
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "get_emp_rs"
cmd.Parameters.Add("p_recordset", OracleDbType.RefCursor).Direction = ParameterDirection.Output
sda.SelectCommand = cmd
Using ds As New System.Data.DataSet("results")
sda.Fill(ds, "MyTableName")
Return ds
End Using
End Using
End Using
Catch ex As Exception
'---------
End Try
End Function

error when trying to update column values in VB.net

Good day!
I just want to seek help from you guys, I'm again having problems with my UPDATE functionality, here's my code...
Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
con = New SqlConnection("Server=localhost\SQLEXPRESS;Database=Vehicle;Trusted_Connection=True;")
con.Open()
Dim cmd As SqlCommand = con.CreateCommand
cmd.CommandText = String.Format("UPDATE trip SET ticketno, charge, driver, destination, passenger, purpose, tripdate", txtticket.Text, txtcharge.Text, txtdriver.Text, txtdestination.Text, txtpassenger.Text, txtpurpose.Text, dtptripdate1.Value)
Dim affectedRows As Integer = cmd.ExecuteNonQuery
If affectedRows > 0 Then
MsgBox("Succesfully Updated")
Else
MsgBox("Failed to update")
End If
con.Close()
End Sub
When I try to click the Button, an error would show:
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near ','.
thanks for helping me out.
I'm really close to finishing this small-scale project for my office but I'm stuck with these kind of problems.
Try this,
Dim myCommand = New SqlCommand("UPDATE trip SET ticketno=#ticketno, charge=#charge, driver=#driver, destination=#destination, passenger=#passenger, purpose=#purpose, tripdate=#tripdate",con)
myCommand.Parameters.Add("#ticketno", txtticket.Text)
myCommand.Parameters.Add("#charge", txtcharge.Text)
myCommand.Parameters.Add("#driver", txtdriver.Text)
myCommand.Parameters.Add("#destination", txtdestination.Text)
myCommand.Parameters.Add("#passenger", txtpassenger.Text)
myCommand.Parameters.Add("#purpose", txtpurpose.Text)
myCommand.Parameters.Add("#tripdate", dtptripdate1.Text)
Dim affectedRows As Integer = cmd.ExecuteNonQuery
If affectedRows > 0 Then
MsgBox("Succesfully Updated")
Else
MsgBox("Failed to update")
End If
con.Close()
Your UPDATE statement is wrong, so your String.Format. and don't your missed out a WHERE condition?
cmd.CommandText = String.Format("UPDATE trip SET ticketno='{0}', charge='{1}', driver='{2}', destination='{3}', passenger='{4}', purpose='{5}', tripdate='{6}'", txtticket.Text, txtcharge.Text, txtdriver.Text, txtdestination.Text, txtpassenger.Text, txtpurpose.Text, dtptripdate1.Value)
OR try this to avoid SQL Injection.
Wrap your conn with a Using block to ensure the dispose of your SqlConnection
Using conn As New SqlConnection("Server=localhost\SQLEXPRESS;Database=Vehicle;Trusted_Connection=True;")
conn.Open()
Dim cmd As New SqlCommand
cmd.Connection = conn
cmd.CommandText = "UPDATE trip SET ticketno=#ticketno, charge=#charge, driver=#driver, destination=#destination, " & _
"passenger=#passenger, purpose=#purpose, tripdate=#tripdate " & _
"WHERE SomeCondition"
cmd.Parameters.AddWithValue("#ticketno", txtticket.Text)
cmd.Parameters.AddWithValue("#charge", txtcharge.Text)
cmd.Parameters.AddWithValue("#driver", txtdriver.Text)
cmd.Parameters.AddWithValue("#destination", txtdestination.Text)
cmd.Parameters.AddWithValue("#passenger", txtpassenger.Text)
cmd.Parameters.AddWithValue("#purpose", txtpurpose.Text)
cmd.Parameters.AddWithValue("#tripdate", dtptripdate1.Value)
Dim affectedRow As Integer = cmd.ExecuteNonQuery
IIf(affectedRow > 0, MsgBox("Succesfully Updated"), MsgBox("Failed to update"))
End Using

How to populate a text box with value from DB

I am new to asp.net and here I am trying to populate a single text box with a value from database.
I have created this code but not working:
Try
Dim MyCon As New SqlConnection("server = servername; uid = sa; pwd =abc; database = master")
Dim MyCommand As New SqlCommand("Select empFirstName from Employees where empid=2")
MyCon.Open()
Dim MyReader = MyCommand.ExecuteReader()
While MyReader.Read()
Dim sqlda = New SqlDataAdapter()
Dim dt As New Data.DataTable()
Dim ds As New Data.DataSet
sqlda.Fill(ds)
TextBox1.Text = ds.Tables(0).ToString
MyCon.Close()
End While
Please correct the code and tell me where I am wrong.
Kindly suggest me a link if any to read more on this topic for beginners with example.
Try this sample, it will work for you http://geekswithblogs.net/dotNETvinz/archive/2008/09/12/bind-textbox-and-label-control-with-data-from-database.aspx
ds.Tables(0)
will return a DataTable
If you want to get the tablename, write this instead:
ds.Tables(0).TableName
If you want to get value returned, write this kind of code:
ds.Tables(0).Rows(0).Item("empFirstName")
This will store only the 1st row from the database
TextBox1.Text = ds.Tables(0).Rows(0)(0).ToString();
Row(0)(0) indicates to get the 1st row from the 1st column
If the query is returning more than 1 rows then u need to iterate the data table and store it in a List(Of String) instead of an array as you don't know the number of rows returned from the query
Dim EmpFirstName As New List(Of String)
Dim myRow As DataRow
Dim myColumn As DataColumn
For Each myRow in dt.Rows
EmpFirstName.Add(myRow(dt.Columns(0)))
Next

Using a stringbuilder as a parameter to a stored procedure and returning a dataset

I have a couple of problems relating to one of the parameters passing a number of values to a stored procedure and the result that comes back converting to dataset in order for this to be bound to an MS ReportViewer.
The error I am getting says that the the reader is closed.
My relevant code snippet is:
Dim _listOfSites As New StringBuilder()
Dim _resultDataSet As DataSet = New DataSet
Using _conn as New SqlConnection()
_conn.ConnectionString = _connString
Try
For i as Integer = 0 To _sites.Count - 1
_listOfSites.Append(_sites(i))
If _sites.Count > 1 Then
_listOfSites.Append(",")
End If
Next
_conn.Open()
Dim _sqlCommand as SqlCommand = New SqlCommand("GetResults", _conn)
_sqlCommand.Parameters.Add("#Sites", SqlDbType.Varchar).Value = _listOfSites
_sqlCommand.Parameters.Add("#Date", SqlDbType.Date).Value = _date
Dim _reader as SqlDataReader = _sqlCommand.ExecuteReader
While _reader.Read
_resultDataSet.Load(_reader, LoadOption.PreserveChanges, New String() {"RegionalResults"})
End While
_reader.Close()
Can anyone please help?
Thanks
Looks like you should not call _reader.Read as _resultDataSet.Load do it by itself and it could close the SqlDataReader. So instead of
Dim _reader as SqlDataReader = _sqlCommand.ExecuteReader
While _reader.Read
_resultDataSet.Load(_reader, LoadOption.PreserveChanges, New String() {"RegionalResults"})
End While
_reader.Close()
Just write
Using _reader as SqlDataReader = _sqlCommand.ExecuteReader
_resultDataSet.Load(_reader, LoadOption.PreserveChanges, New String() {"RegionalResults"})
End Using
Hope that helps

ASP.NET - Could not find stored procedure

I've been searching the depths of the internet and all the solutions I found did not solve this problem.
I am using Visual Web Developer 2010 Express with SQL Server 2008, using VB.
I am trying to execute a stored procedure to insert some data coming from a textbox control to a database, if the id doesn't exist it inserts both the id given in the textbox and the current date (time_scanned_in), if the id exists already, it will insert the current datetime in the [time_scanned_out] column, if all 3 fields in the db are full, it will return #message = 1.
Here is the sql stored procedure:
ALTER PROCEDURE dbo.InsertDateTime
#barcode_id nchar(20),
#message char(1) = 0 Output
AS
BEGIN
if not exists(select * from tblWork where barcode_id = #barcode_id)
begin
INSERT INTO [tblWork] ([barcode_id], [time_scanned]) VALUES (#barcode_id, GetDate())
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NOT NULL )
begin
SET #message=1
end
else if exists(select * from tblWork where barcode_id = #barcode_id AND time_scanned_out IS NULL)
begin
UPDATE [tblWork] SET [time_scanned_out] = GetDate() WHERE [barcode_id] = #barcode_id
end
RETURN #message
end
If I execute this (by right clicking on the SP), it works flawlessly and returns the values when all fields have been filled.
But when executed through the vb code, no such procedure can be found, giving the error in the title.
Here is the vb code:
Dim opconn As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"
Dim sqlConnection1 As New SqlConnection(opconn)
Dim cmd As New SqlCommand
Dim returnValue As Object
cmd.CommandText = "InsertDateTime"
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = sqlConnection1
sqlConnection1.Open()
With cmd.Parameters.Add(New SqlParameter("#barcode_id", TextBox.Text))
End With
With cmd.Parameters.Add(New SqlParameter("#message", SqlDbType.Char, 1, Label3.Text))
End With
returnValue = cmd.ExecuteScalar()
sqlConnection1.Close()
Note, I haven't done the code for the return part yet, will do that once I get it to locate the SP.
Tried listing all objects with the sys.objects.name for each of the databases in a gridview, it listed everything but the stored procedure I want.
Why is this, any ideas? Would be much appreciated, spent hours trying to find a solution.
If anyone needs any more code or information feel free to ask.
try cmd.parameters.clear() first and then start adding parameters in cmd object. also instead of cmd.executescaler(), try cmd.executenonquery or cmd.executeReader()
Try this
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
SqlParameter prmOut = cmd.Parameters.Add("#message",SqlDbType.Char, 1)
prmOut.Value = Label3.Text
prmOut.Direction = ParameterDirection.InputOutput
cmd.ExecuteNonQuery()
returnValue = prmOut.Value.ToString()
Recreated the whole project with a whole new database, copied all the same code, and now it all works flawlessly! Still have no idea what was wrong, but thank you all, you were all prompt and knowledgable.
Here was the final VB code for anyone who's interested:
Dim myConnection As New SqlConnection(opconn)
Dim cmd As New SqlCommand()
Dim myReader As SqlDataReader
cmd.CommandType = CommandType.StoredProcedure
cmd.Connection = myConnection
cmd.CommandText = "InsertTimes"
cmd.Parameters.AddWithValue("#message", OleDbType.Integer)
cmd.Parameters.AddWithValue("#barcode_id", TextBox.Text)
cmd.Parameters("#message").Direction = ParameterDirection.Output
Try
myConnection.Open()
myReader = cmd.ExecuteReader()
Dim returnMessage As String = cmd.Parameters("#message").Value
If returnMessage = 1 Then
label_confirmation.Text = "Record successfully submitted!"
TextBox.Text = ""
ElseIf returnMessage = 2 Then
label_confirmation.Text = "A finish time already exists for the record '" & TextBox.Text & "', would you like to override the finish time anyway?"
button_yes.Visible = True
button_no.Visible = True
ElseIf returnMessage = 3 Then
label_confirmation.Text = "Record submitted, work operation status complete!"
TextBox.Text = ""
End If
Catch ex As Exception
label_confirmation.Text = ex.ToString()
Finally
myConnection.Close()
End Try

Resources