I made a basic program that connects and gets content from a table via SQL, it's working normally. What I want is; when connection losts via SQL Server or internet connection, it must continue to list items that it got before connection losts instead of giving "Connection Problem Error".
Code is like this:
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
Dim conn As New SqlConnection
conn.ConnectionString = baglan()
conn.Open()
strSQL = "SELECT * FROM Telefon_Otomasyon"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim dset As New DataSet()
da.Fill(dset, "Telefon_Otomasyon")
Dim Hepsi As DataRow
For Each Hepsi In dset.Tables("Telefon_Otomasyon").Rows
Response.Write(Hepsi("Arayan") & "<br />")
Next
End Sub
Thanks!
What you can do is store your dataset in Session: (excuse my VB, i'm very rusty with it)
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Dim strSQL As String
Dim conn As New SqlConnection
conn.ConnectionString = baglan()
conn.Open()
strSQL = "SELECT * FROM Telefon_Otomasyon"
Dim da As New SqlDataAdapter(strSQL, conn)
Dim dset As New DataSet()
Try
da.Fill(dset, "Telefon_Otomasyon")
MyDataset = dset
Catch ex As SqlException
dset = MyDataset
End Try
Dim Hepsi As DataRow
For Each Hepsi In dset.Tables("Telefon_Otomasyon").Rows
Response.Write(Hepsi("Arayan") & "<br />")
Next
End Sub
Private Property MyDataset() As DataSet
Get
return Session("myDataset")
End Get
Set(ByVal value as DataSet)
Session("myDataset") = value
End Set
End Property
This is also a very basic example, it needs to be tidied up before you can use it in production code, i.e. you need to consider what to do if there is no dataset stored in Session (if it returns null). You may want to be a bit smarter than that and just store a specific table. Note that Session can expire though, so do some reading on it. This should be enough to steer you in the right direction.
Further note: if you want something a little less volatile than Session then you could try using the Cache instead.
I'm not sure I understand the problem here. While I'm not a VB-programmer it seems to me like once the page loads it will run the SQL query and then process that dataset.
If you reload the page and the SQL connection isn't working you will get an error that you'd need to handle somehow (not sure how VB exceptions work but I'm sure you can figure that out).
If you on the other hand mean that you want to get whatever data you can from a query that gets disconnected mid-query - I'd say that is pretty hard and only relevant for huge queries.
Related
I am having a library system database. I want to include a search box where I can search for a book name. I am using sql server. I know how to write a sql statement using the LIKE %''% clause, but the thing is I am writing this sql statement in a separate file and include that in the sub method in vb.net. How can I make that statement use the text entered in textbox?
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim str As String = ("Data Source=.\INSTANCE;initial catalog=example;user=sa;password=gariahat")
Dim con As New SqlConnection(str)
Dim cmd As New SqlCommand("select * from item where book_id like '%" + Trim(TextBox1.Text) + "%'", con)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
If (da.Fill(ds, "item")) Then
ItemDataGridView.DataSource = ds.Tables(0)
MessageBox.Show("match found")
Else
MessageBox.Show("match not found")
End If
End Sub
I know this sub will work if I include the sql statement in the sub itself. But I use squaler to store my sql stored procedures and use those file in my sub, that file does not accept 'textbox.text'.
Example:
Public Shared Sub AccountDeposit(ByVal value As Integer, ByVal AccountNumber As String, ByVal connection As SqlConnection)
Dim cmd As New SqlCommand("AccountDeposit", connection)
cmd.CommandType = Data.CommandType.StoredProcedure
cmd.Parameters.AddWithValue("#AccountNumber", AccountNumber)
cmd.Parameters.AddWithValue("#Value", value)
cmd.ExecuteNonQuery()
End Sub
Here "AccountDeposit" is my stored procedure which i included in my sub.I want to do similar thing here but dont know how to include the text in textbox to sql statement
This is my first time asking a question and I've been searching for 2 days to find an answer. Hopefully one of you masters can assist.
I have a 4 column listview populated from a sql table. The table doesn't allow duplicates. I simply want to be able to catch that error and give a friendly message to the user that the item is already in the list. I have found multiple solutions that don't work (probably my error).
Below is the one that I had the most hope for... but nothing.
Still getting "Violation of PRIMARY KEY constraint 'PK_tbl.associateNames'. Cannot insert duplicate key in object 'dbo.tbl.associateNames'.
The statement has been terminated"
Protected Sub listviewInserting_itemInserted(ByVal sender As Object, ByVal e As ListViewInsertEventArgs)
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Try
con.ConnectionString = "Data Source=server\instance; Initial Catalog=sears;User Id=johnnyFive;Password=alive;"
con.Open()
cmd.Connection = con
cmd.CommandText = "INSERT INTO [tbl.associateNames] ([orderIssuer], [associateName], [department]) VALUES (#orderIssuer, #associateName, #department)"
cmd.ExecuteNonQuery()
Catch ex As SqlException
MsgBox("Duplicate Entry found", MsgBoxStyle.Information, "Dups")
e.Cancel = True
End Try
End Sub
ANY suggestions would be appreciated! Thanks.
Should work. Perhaps the wrong type of execption? What happens if you enlarge the catch to
Catch ex As Exception
I am officially an idiot.
Had I remembered to put this line like this (i.e. add the Handles blah blah) I wouldn't have had the issue.
Protected Sub listviewInserting_itemInserted(ByVal sender As Object, e As ListViewInsertEventArgs) Handles ListView1.ItemInserting
Dim con As New SqlConnection
Dim cmd As New SqlCommand
Sorry if this question is stupid but I have no other way to see the big picture.
I have 1 textbox, 1 label and database with two columns (codename and description), by entering codename in textbox I would like to get corresponding description in label.
With Excel and VBA it can be done with couple of lines. Sadly I can not use Excel but have to choose Web interface 'cause of slow PCs and Office price. Why is this simple task so complicated in ASP.NET with all general declarations and sqlservers and sqlconnections.
Is there a simpler way to do this?
BTW. I've tried to adapt many different things I've found on the web and this last one looks promising but it doesn't work :
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Using sqlconn As New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=KLIJENTI;Integrated Security=True"), _
sqlcmd As New SqlCommand("Select From Baza Where SIFRE = #SIFRE", sqlconn)
sqlcmd.Parameters.Add("#SIFRE", SqlDbType.VarChar, 50).Value = TextBox2.Text
sqlconn.Open()
'Label1.Text = CString(sqlcmd.ExecuteScalar()) 'CString is not declared
Label1.Text = sqlcmd.ExecuteScalar()
End Using
End Sub
Where Baza is Table name,
SIFRE is codename that will be entered in textbox
and NAZIV is description corresponding to SIFRE and should be shown in Label
The correct form is
Protected Sub TextBox2_TextChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles TextBox2.TextChanged
Using sqlconn = New SqlConnection("Data Source=.\sqlexpress;Initial Catalog=KLIJENTI;Integrated Security=True")
Using sqlcmd = New SqlCommand("Select NAZIV From Baza Where SIFRE = #SIFRE", sqlconn)
sqlcmd.Parameters.AddWithValue("#SIFRE", TextBox2.Text)
sqlconn.Open()
Dim result = sqlcmd.ExecuteScalar()
if result IsNot Nothing Then
Label1.Text = result.ToString
End If
End Using
End Using
End Sub
The SELECT sql clause is followed by the list of columns you want to retrieve. (Added NAZIV)
Also you should consider that your query could not find a value for the parameter #Sifre and, in that case, the result of the ExecuteScalar is Nothing.
Please have a look at the code below, which I have written as a test. It does not make the ASP.NET process grow too much:
Private Sub Form1_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Try
Dim Test As Integer
For Test = 0 To 1000000
Test1()
Next
Dim Test2 As String = "Test"
Catch ex As Exception
End Try
End Sub
Public Sub Test1()
Try
Dim objCommand As New SqlCommand
Dim strConString As String = "Data Source=IANSCOMPUTER;Initial Catalog=Test;Integrated Security=True"
Dim objCon As New SqlConnection
objCon.ConnectionString = strConString
objCon.Open()
objCommand.Connection = objCon
objCommand.CommandText = "select * from person "
Dim objDR As SqlDataReader = objCommand.ExecuteReader
If objDR.HasRows Then
Using objCon
End Using
End If
Catch ex As Exception
'I don't swallow exceptions.
End Try
End Sub
End Class
I am trying to detect a memory leak. I have found code similar to the above in the affected project. I notice that objCommand.dispose is not called. The project in question connects to an Oracle database and an SQL database. When connecting to an SQL database the above code is used. When connecting to an Oracle database Oracle.dataaccess.dll is used and the code looks different to reflect this.
My specific question is: if I avoid calling sqlcommand.dispose then will this cause a memory leak over time?
If a class has a Dispose method, that isn't getting called, then it is likely to be the source of a memory leak. Use Using, and it will call the Dispose method for you.
Your second example should look like the below, where all disposable object are wrapped in using blocks.
Dim strConString As String = "Data Source=IANSCOMPUTER;" +
"Initial Catalog=Test;Integrated Security=True"
Dim sqlStr as String = "select * from person "
Using objCon As New SqlConnection(strConString)
Using objCommand As New SqlCommand(sqlStr, objCon)
objCon.Open()
Using objDR As SqlDataReader = objCommand.ExecuteReader
If objDR.HasRows Then
End If
End Using
End Using
End Using
I am trying to loop through a datatable, that will pass information to my stored procedure but it isn't working.
even though it works when i manuelly
Protected Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim dv As New DataView
Dim dt As New DataTable
dv = SqlDataSource1.Select(DataSourceSelectArguments.Empty)
dt = dv.ToTable()
For Each row As DataRow In dt.Rows
If row("vtr_gen10").ToString() = "y" Or row("vn10").ToString() = "a" Or row("vtr_gen10").ToString() = "p" Then
Dim SQLCon As New SqlClient.SqlConnection
Dim sqlcmd As New SqlCommand
SQLCon.ConnectionString = SqlDataSource2.ConnectionString
SQLCon.Open()
sqlcmd.CommandText = "protest" ' Stored Procedure to Call
sqlcmd.CommandType = CommandType.StoredProcedure 'Setup Command Type
sqlcmd.Connection = SQLCon 'Active Connection
sqlcmd.Parameters.AddWithValue("#ID", row("id"))
sqlcmd.Parameters.AddWithValue("#Value", "Y")
sqlcmd.ExecuteNonQuery()
SQLCon.Close()
End If
Next
End Sub
Are you absolutely sure the IF criteria is being met after the first two records? One thing to look for is spaces or other string anomalies such as carraige returns in your database...
Row("vn10").ToString for example may for some reason be "a " instead of "a". Might be worth putting in a temporary debug line such as :
Throw New Exception("[" & Row("vn10").ToString & "]")
or inspect length on some records that erroneously fail.
There is nothing seems to be wrong with your code, but if you think its because its moving too fast, try adding sleep using System.Threading.Thread.Sleep(milliseconds)