Read Data From SQL using Webservice VB.NET - asp.net

i have a program to read data from sql server using vb .net web service but i have an error when i run my code like this
http://prntscr.com/apmahp
my code
<WebMethod()> _
Public Function TopKill() As Integer
Dim con As New SqlConnection
con.ConnectionString = "Data Source=127.0.0.1;Initial Catalog=RF_User;Integrated Security=True"
Dim killing As Integer
con.Open()
Dim cmd As New SqlCommand(("SELECT TOP 20 Name, [Kill], Death FROM tbl_pvporderview Join(tbl_base) ON tbl_pvporderview.serial = tbl_base.Serial ORDER BY [Kill] DESC"), con)
Dim killreader As SqlDataReader
killreader = cmd.ExecuteReader()
killreader.Read()
If killreader.HasRows Then
killing = killreader.Item("Name").ToString
killing = killreader.Item("Kill").ToString
killing = killreader.Item("Death").ToString
End If
con.Close()
Return killing
End Function ' TOP 20 Killer
i don't know how to fix it.
any one can help me to fix my code
thanks before

Mind the spaces, use the edited query below
Dim cmd As New SqlCommand(("SELECT TOP 20 Name, [Kill], Death FROM tbl_pvporderview Join tbl_base ON tbl_pvporderview.serial = tbl_base.Serial ORDER BY [Kill] DESC"), con)
This should work because there was a space missing after the Join
Hope this helped

Related

Execute Scalar to Label. Subquery returned more than 1 value

So I have a label which shows the username of the user. I've used this value to return their ID which I then attach to a label. I used execute scalar to do this because I wasn't sure how else to get a single value on a label.
This works fine. I then use the ID from the label and put it in another table. I can do this twice and then the page crashes saying...
"Subquery returned more than 1 value. This is not permitted when the subquery follows =, !=, <, <= , >, >= or when the subquery is used as an expression."
However I don't understand. I don't pull anything from the second table on the page. I don't know why it would affect it. I feel like I've tried everything. Taking out the line that posts the ID to the label lets the page run but I need it there.
Label2.Text = User.Identity.Name
Dim connetionString As String
Dim cnn As SqlConnection
Dim cmd As SqlCommand
Dim sql As String
connetionString = "Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True"
sql = "SELECT SupID FROM Supervisor WHERE (Email = #Email)"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
cmd = New SqlCommand(sql, cnn)
cmd.Parameters.Add(New SqlParameter("#Email", User.Identity.Name))
Dim supid1 As Int32 = Convert.ToInt32(cmd.ExecuteScalar())
cmd.Dispose()
cnn.Close()
Label1.Text = supid1.ToString
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
This should return the first result for you. Also, it's a good idea to employ Using blocks for objects such as connections, commands, and readers.
Using cn = New SqlConnection("Data Source=(LocalDB)\v11.0;AttachDbFilename=|DataDirectory|\FYPMS_DB.mdf;Integrated Security=True")
cn.Open()
Using cmd = New SqlCommand("SELECT SupID FROM Supervisor WHERE Email = #Email", cn)
cmd.Parameters.AddWithValue("#Email", User.Identity.Name)
Using dr = cmd.ExecuteReader
If dr.Read Then
Label1.Text = CInt(dr("SupID"))
End If
End Using
End Using
End Using
If you are not sure there are multiple rows for same email in that table, you can change the query to following, that will work for you with executescalar.
SELECT TOP 1 SupID FROM Supervisor WHERE (Email = #Email)
Horribly sorry! But yes you were right! There was another query going on in the background that I never noticed that was affecting it all. So sorry

oracle clob parameter conversion to string hangs in asp.net

Please find this code. It is properly working on my local machine. It was copied to windows server 2008 (64bit). It was working fine for many days. But now, it is hanging and taking 20 minutes. Same code is working in my machine fast. If I convert clob to varchar, it will work, but it will not support more than 32 K. I updated oracle client, now also it is hanging.
Dim cn As New OracleConnection(ConfigurationManager.ConnectionStrings("ConnectionString").ConnectionString)
Dim cmd As New OracleCommand
cn.Open()
cmd.Connection = cn
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.CommandText = "Inet_Pkg_Menu.TopMenu"
cmd.Parameters.Add("pBrCode", OracleDbType.Int32).Direction = Data.ParameterDirection.Input
cmd.Parameters.Add("pRes", OracleDbType.Clob).Direction = Data.ParameterDirection.Output
cmd.Parameters(0).Value = Session("user_code")
cmd.ExecuteNonQuery()
Dim s As String
Dim olob As OracleClob
olob = CType(cmd.Parameters("pRes").Value, OracleClob)
s = System.Convert.ToString(olob.Value) 'Hanged line
I'm using Oracle Clob and it is very easy and there is no need to make type conversion, just suppose it as a string in asp.net, and here is an example:
Dim sql = "select xmlagg(XMLElement("user",xmlattributes(user_id "user_id"))).getClobVal() from users" 'this is just example of returning clob value
Dim adp As New Data.OleDb.OleDbDataAdapter(sql, MyConnectionString)
Dim dt As New DataTable
adp.Fill(dt)
Dim data As String = dt.Rows[0][0].toString()
and now in data variable you have the result

ASP.NET SqlConnection error: "The ConnectionString property has not been initialized"

What's wrong this T-SQL query :
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim SQLData As New System.Data.SqlClient.SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
Dim cmdSelect As New System.Data.SqlClient.SqlCommand("SELECT COUNT(*) FROM Table1 WHERE Name ='" + TextBox1.Text + "'", SQLData)
SQLData.Open()
If cmdSelect.ExecuteScalar > 0 Then
Label1.Text = "You have already voted this service"
Return
End If
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO Tabel1 (Name) VALUES('" & Trim(Label1.Text) & "')"
cmd.ExecuteNonQuery()
Label1.Text = "Thank You !"
SQLData.Close()
End Sub
Your problem is that you are opening a connection (SQLData), ignoring it, then trying to open a new connection (con) without giving it a connection string. Instead of this:
Dim con As New SqlConnection
Dim cmd As New SqlCommand
con.Open()
cmd.Connection = con
you should have:
Dim cmd As New SqlCommand
cmd.Connection = SQLData
Also, it is very bad practice to insert string value inline in SQL as you have.
I would recommend an approach something like this:
Protected Function Button1_Click(sender As Object, e As System.EventArgs)
' define and create your one single SqlConnection and protect it by using a "using()....." block
Using _connection As New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\Database.mdf;Integrated Security=True;User Instance=True")
' define and craete your SqlCommand to count your occurences and make it a proper, parametrized query
Using cmdSelect As New SqlCommand("SELECT COUNT(*) FROM dbo.Table1 WHERE Name = #Name", _connection)
' add the parameter to your SqlCommand, define the datatype and length
cmdSelect.Parameters.Add("#Name", SqlDbType.VarChar, 100)
' set the value for that parameter
cmdSelect.Parameters("#Name").Value = TextBox1.Text.Trim()
' open connection, execute query, set return value
_connection.Open()
If cmdSelect.ExecuteScalar() > 0 Then
Label1.Text = "You have already voted this service"
Return
End If
End Using
' define second query to insert data reusing the existing connection
Using cmdInsert As New SqlCommand("INSERT INTO dbo.Table1(Name) VALUES(#Name)", _connection)
' add the parameter to your SqlCommand, define the datatype and length
cmdInsert.Parameters.Add("#Name", SqlDbType.VarChar, 100)
' set the value for that parameter
cmdInsert.Parameters("#Name").Value = Label1.Text.Trim()
cmdInsert.ExecuteNonQuery()
End Using
_connection.Close()
End Using
Label1.Text = "Thank You !"
End Function
Points to consider:
you have one SqlConnection - that's good enough for both queries, reuse it!
always put your disposable objects like SqlConnection, SqlCommand into Using..... blocks to protect them and make sure they get properly disposed
always use parametrized queries - do NOT under any circumstances just concatenate together your SQL statements - that's a big huge gaping security hole, inviting SQL injection attacks - just DON'T do it - EVER!
if I could, I would try to separate your UI elements from the code - try to put this code into a separate method that will take in the string values from the caller, and will return a result string to be set on the UI (Label1.Text=). Mixing code that queries the database and setting the UI at the same time is messy and leads to spaghetti code - try to separate those things
put your connection string into the web.config into the <connectionStrings> section and read it from there - don't have your connection string as a string literal all throughout your code!
There's a few things I see wrong there. First, (other than the SQL injection vulnerability) is that you typed Table1 once, and Tabel1 the other time. While that could be what you want, I doubt it. Next you're creating a second connection. That doesn't seem to be needed. Use the existing SQLData object instead of con. You can also reduce the lines starting from the declaration of cmd (inclusive) to the ExecuteNonQuery call (exclusive) with this:
Dim cmd As New SqlCommand("INSERT INTO Tabel1 (Name) VALUES('" & Trim(Label1.Text) & "')", SQLData)
Now back to that SQL injection vulnerability. What if someone's name is "James O'Brian" (or something else with an apostrophe in it)?

oRecordset in ASP.NET mySQL

I have this mySQL code that connects to my server. It connects just fine:
Dim MyConString As String = "DRIVER={MySQL ODBC 3.51 Driver};" & _
"SERVER=example.com;" & _
"DATABASE=xxx;" & _
"UID=xxx;" & _
"PASSWORD=xxx;" & _
"OPTION=3;"
Dim conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "select * from userinfo WHERE emailAddress = '" & theUN & "'""
MyCommand.ExecuteNonQuery()
conn.Close()
However, i have an old Classic ASP page that uses "oRecordset" to get the data from the mySQL server:
Set oConnection = Server.CreateObject("ADODB.Connection")
Set oRecordset = Server.CreateObject("ADODB.Recordset")
oConnection.Open "DRIVER={MySQL ODBC 3.51 Driver}; SERVER=example.com; PORT=3306; DATABASE=xxx; USER=xxx; PASSWORD=xxx; OPTION=3;"
sqltemp = "select * from userinfo WHERE emailAddress = '" & theUN & "'"
oRecordset.Open sqltemp, oConnection,3,3
And i can use oRecordset as follows:
if oRecordset.EOF then....
or
strValue = oRecordset("Table_Name").value
or
oRecordset("Table_Name").value = "New Value"
oRecordset.update
etc...
However, for the life of me, i can not find any .net code that is similar to that of my Classic ASP page!!!!!
Any help would be great! :o)
David
This is what you have to do:
instead of MyCommand.ExecuteNonQuery you should use MyCommand.ExecuteQuery and assign it to DataReader.
Check out this sample:
Dim myConnection As SqlConnection
Dim myCommand As SqlCommand
Dim dr As New SqlDataReader()
'declaring the objects
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs)_
Handles MyBase.Load
myConnection = New SqlConnection("server=localhost;uid=sa;pwd=;database=pubs")
'establishing connection. you need to provide password for sql server
Try
myConnection.Open()
'opening the connection
myCommand = New SqlCommand("Select * from discounts", myConnection)
'executing the command and assigning it to connection
dr = myCommand.ExecuteReader()
While dr.Read()
'reading from the datareader
MessageBox.Show("discounttype" & dr(0).ToString())
MessageBox.Show("stor_id" & dr(1).ToString())
MessageBox.Show("lowqty" & dr(2).ToString())
MessageBox.Show("highqty" & dr(3).ToString())
MessageBox.Show("discount" & dr(4).ToString())
'displaying the data from the table
End While
dr.Close()
myConnection.Close()
Catch e As Exception
End Try
HTH
Dim conn As OdbcConnection = New OdbcConnection("DRIVER={MySQL ODBC 3.51 Driver}; SERVER=xxx.com; DATABASE=xxx; UID=xxx; PASSWORD=xxx; OPTION=3;")
conn.Open()
Dim MyCommand As New OdbcCommand
MyCommand.Connection = conn
MyCommand.CommandText = "SELECT * FROM userinfo"
Dim rst = MyCommand.ExecuteReader()
While rst.Read()
response.write(rst("userID").ToString())
End While
conn.Close()
Dim email As String = "anyone#anywhere.com"
Dim stringValue As String
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql = "Select ... From userInfo Where emailAddress = #Email"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
Dim reader As OdbcDataReader = cmd.ExecuteReader()
While reader.Read()
stringValue = reader.GetString(0)
End While
End Using
conn.Close()
End Using
'To do an Update
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Update userInfo Set Column = #Value Where PK = #PK"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Email", email)
cmd.ExecuteNonQuery()
End Using
End Using
'To do an Insert
Using conn As OdbcConnection = New OdbcConnection(MyConString)
conn.Open()
Dim sql As String = "Insert userInfo(Col1,Col2,...) Values(#Value1,#Value2...)"
Using cmd As OdbcCommand = New OdbcCommand(sql, conn)
cmd.Parameters.AddWithValue("#Col1", value1)
cmd.Parameters.AddWithValue("#Col2", value2)
...
cmd.ExecuteNonQuery()
End Using
End Using
First, even in ASP Classic, it is an absolutely horrid approach to concatenate a value directly into a SQL statement. This is how SQL Injection vulnerabilities happen. You should always sanitize values that get concatenated into SQL statements. In .NET, you can use parametrized queries where you replace the values that go into your query with a variable that begins with an # sign. You then add a parameter to the command object and set your value that way. The Command object will sanitize the value for you.
ADDITION
You mentioned in a comment that your ASP Classic code is shorter. In fact, the .NET code is shorter because there are a host of things happening that you do not see and have not implemented in your ASP Classic code. I already mentioned one which is sanitizing the inputs. Another is logging. Out of the box, if an exception is thrown, it will log it in the Event Log with a call stack. To even get a call stack in ASP Classic is a chore much less any sort of decent logging. You would need to set On Error Resume Next and check for err.number <> 0 after each line. In addition, without On Error Resume Next, if an error is thrown, you have no guarantee that the connection will be closed. It should be closed, but the only way to know for sure is to use On Error Resume Next and try to close it.
Generally, I encapsulate all of my data access code into a set of methods so that I can simply pass the SQL statement and the parameter values and ensure that it is called properly each time. (This holds true for ASP Classic too).

ASP.NET Database Connect

Hello when i run my application on server, the connection doesn't open
--> my dataset is still closed
Dim strconnect As String = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + "rootPath" + "\" + "VSS_TESTDB.mdb" + "Persist Security Info=False"
Dim objConnection As New OleDbConnection(strconnect)
Dim sql As String = "SELECT VSS_Files.id, VSS_Files.filename,VSS_Files.dateOfCreation,VSSDirs.dir FROM VSS_Files , VSSDirs Where VSS_Files.dir_id = VSSDirs.id;"
Dim cmd As New OleDbCommand(sql, objConnection)
Dim myDataReader As OleDbDataReader
myDataReader = cmd.ExecuteReader()
what can i do?
greetings tyzak
You need to create an OleDbConnection using an OleDbConnectionStringBuilder to connect to the database.
For example:
Dim builder As New OleDbConnectionStringBuilder
builder.Provider = "Microsoft.Jet.OLEDB.4.0"
builder.DataSource = Path.Combine(rootPath, "VSS_TESTDB.mdb")
builder.PersistSecurityInfo = False
Using connection As New OleDbConnection(builder.ToString())
Using command As New OleDbCommand("SELECT VSS_Files.id, VSS_Files.filename,VSS_Files.dateOfCreation,VSSDirs.dir FROM VSS_Files, VSSDirs Where VSS_Files.dir_id = VSSDirs.id;", connection)
connection.Open()
Using reader As OleDbDataReader = command.ExecuteReader()
'Do something
End Using
End Using
EDIT: Your problem is probably that you put quotes around rootPath. The Data Source of your connection string is DataSource=rootPath\VSS_TESTDB.mdb. I assume that you actually want it to have the value of the rootPath variable.
Also, you need to open the connection.
Finally, you should close the connection and the DataReader using the Using statement.
See my updated example.
This question is pretty vague, and it is difficult to properly diagnose from one line of code. Here are a couple of suggestions:
You need to assign this connection string to a connection object.
See http://www.connectionstrings.com/ for the full and proper form for connection strings.

Resources