How can I make my adodc connect faster to my SQL Server? It's taking a minute (so long) before I can view thousand of record in my listview. Please anyone help me.
I'm using this code:
Public Class McheckpaymentNew
Private cn As New ADODB.Connection
Private rs As New ADODB.Recordset
Private Sub McheckpaymentNew_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Try
cn.ConnectionString = "DSN=database; UID=user; PWD=password"
cn.Open()
rs.CursorLocation = ADODB.CursorLocationEnum.adUseClient
rs.CursorType = ADODB.CursorTypeEnum.adOpenStatic
rs.LockType = ADODB.LockTypeEnum.adLockBatchOptimistic
Catch ex As Exception
MsgBox("Failed to Connect!, Please check your Network Connections, or Contact MIS Dept. for assistance.", vbCritical, "Error while Connecting to Database.."
End
End Try
End Sub
End Class
Related
I get the following error when trying to launch my windows application in another machine.
"A network-related or instance-specific error occurred while
establishing a connection to SQL Server. The server was not found or
was not accessible. Verify that the instance name is correct and that
SQL Server is configured to allow remote connections. (Provider: Named
Pipes Provider, error: 40 - Could not open a connection to SQL
Server)."
In my machine the app is working but in the user's machine it doesn't work. I have tried a lot of solutions whether in stackoverflow or another website, where none of them helped me to solve this problem. The database is local, so i'm not using any servers or something like that. And the strange thing is that the Log in form is actually working but the other forms are not working. This is a code from one of the forms that are not working to make the idea closer. I hope that you can help me to solve this problem cause I am really running out of time. I'm using VB.NET and SQL SERVER.
Imports System.Data
Imports System.Data.SqlClient
Public Class Form13
'Dim cmd As New SqlCommand
Dim cn As New SqlConnection("database=Leave_manager;server=(local);integrated security=true")
Private Sub Form13_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'TODO: cette ligne de code charge les données dans la table 'Leave_managerDataSet1.Addemployees'. Vous pouvez la déplacer ou la supprimer selon vos besoins.
Me.AddemployeesTableAdapter.Fill(Me.Leave_managerDataSet1.Addemployees)
End Sub
Private Sub ComboBox1_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ComboBox1.SelectedIndexChanged
Try
cn.Open()
Dim sqlcmd As New SqlCommand("select Fname,Lname from Addemployees where ID = '" & ComboBox1.Text & "'", cn)
Dim myreader As SqlDataReader
myreader = sqlcmd.ExecuteReader()
myreader.Read()
If myreader.HasRows Then
TextBox2.Text = myreader.Item("Fname").ToString
TextBox1.Text = myreader.Item("Lname").ToString
End If
cn.Close()
Catch ex As Exception
MessageBox.Show("Error while connecting to SQL Server." & ex.Message)
Finally
cn.Close()
End Try
Try
cn.Open()
Dim sqlcmd As New SqlCommand("SELECT Leave_num FROM Addemployees WHERE ID='" & ComboBox1.Text & "'", cn)
Dim myreader1 As SqlDataReader
myreader1 = sqlcmd.ExecuteReader()
myreader1.Read()
If myreader1.HasRows Then
TextBox6.Text = myreader1.Item("Leave_num").ToString
End If
cn.Close()
Catch
MessageBox.Show("Error!", "exit", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End Sub
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox6.Clear()
Me.CheckBox1.Checked = False
Me.Hide()
Form6.Show()
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If MessageBox.Show("Do you really want to Restore is record?", "Record", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
Try
cn.Open()
Dim cmd As New System.Data.SqlClient.SqlCommand
Dim RA As Integer
cmd = New SqlCommand("update Addemployees set Leave_num ='" & TextBox3.Text & "' where ID='" & ComboBox1.Text & "' ", cn)
cmd.Connection = cn
RA = cmd.ExecuteNonQuery()
MessageBox.Show("Process successful!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
cn.Close()
Catch
MessageBox.Show("Error!", "exit", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
End If
End Sub
Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
If MessageBox.Show("Do you really want to Restore all records?", "Record", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) = Windows.Forms.DialogResult.Yes Then
If Me.TextBox4.ReadOnly = False Then
Try
cn.Open()
Dim cmd2 As New System.Data.SqlClient.SqlCommand
Dim Rb As Integer
cmd2 = New SqlCommand("update Addemployees set Leave_num ='" & TextBox4.Text & "'", cn)
cmd2.Connection = cn
Rb = cmd2.ExecuteNonQuery()
MessageBox.Show("Process successful!", "Save", MessageBoxButtons.OK, MessageBoxIcon.Information)
cn.Close()
Catch
MessageBox.Show("Error!", "exit", MessageBoxButtons.OK, MessageBoxIcon.Error)
End Try
ElseIf Me.TextBox4.ReadOnly = True Then
MessageBox.Show("Error!, please select selectr all option", "exit", MessageBoxButtons.OK, MessageBoxIcon.Error)
End If
End If
End Sub
Private Sub Button3_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button3.Click
TextBox1.Clear()
TextBox2.Clear()
TextBox3.Clear()
TextBox4.Clear()
TextBox6.Clear()
Me.CheckBox1.Checked = False
End Sub
Private Sub CheckBox1_CheckedChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles CheckBox1.CheckedChanged
If Me.CheckBox1.Checked = True Then
Me.TextBox4.ReadOnly = False
ElseIf Me.CheckBox1.Checked = False Then
Me.TextBox4.ReadOnly = True
End If
End Sub
Private Sub Button5_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
End Sub
End Class`
The error - "(Provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)" points out to configuration error on SQL Server part. Please check and ensure that the server accepts connections through named pipes.
"In my machine the app is working but in the user's machine it doesn't work." .......a) Please check the firewall for access of port 1433 (or any other defined port),
b) Please go to services on the user's machine, restart 'SQL Server'
c) In services itself, restart 'Windows firewall', if required.
"And the user when he enter the password and username, the application works and he moves to the next form where the problem occures."..Seems each of your form requires authentication.
I suggest you to take off the database from the user's machine, move to yours, provide access to the user's machine and test from user's machine. You need to create a SQL server user (and not as a windows user for remote machine) and test it. I believe this should take care of DB connectivity issue.
Depends on your sqlserver version.
Check your server name just open cmd and type SQLCMD -L.
Check your server instance name sqllocaldb i.
In sql server express 2012 normally instance name is (LocalDB)\v11.0.
I am writing a simple SQL Server query operation through vb.net application. I am having some strange problems.
This line is giving error:
dr = cmd.ExecuteReader()
This is giving me error "Invalid column name abhishek." Here abhishek is the data I am providing in TextBox1.Text. I am not able to think of any mistake by my side as this is a simple query. I am able to run other queries, like delete queries, on same table in a different form, so its not a database problem.
Any clue what's going wrong?
reginfo is the table name. name is one of the fields.
My complete code is below:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form9
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cmd.CommandText = "select * from reginfo where name=" + (TextBox1.Text) + ""
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader() '<<< This line is creating problem
If dr.Read() Then
TextBox2.Text = dr(0).ToString()
End If
con.Close()
End Sub
Private Sub Form8_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data Source=ABHISHEK-PC\SQLEXPRESS;Initial Catalog=locserver;Integrated Security=True;Pooling=False"
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
End Sub
End Class
if the name field is a text field then you need to enclose your textbox in single quotes, but this is bad advice to give. The only good approach to this kind of situations is through a parameterized query
cmd.CommandText = "select * from reginfo where name=#name"
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader()
Also, do not keep global objects like a connection or a command. It is always a good practice to instantiate a connection as late as possible and close it as soon as possible, better inside a Using block
Using con = New SqlConnection(...connection string here....)
Using cmd = New SqlCommand("select * from reginfo where name=#name", con)
con.Open()
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Using dr = cmd.ExecuteReader
'.... do you reading
End Using
End Using
End Using
In this way the connection is kept open for the minimum time possible and, also in case of exceptions is closed and disposed appropriately.
I have a mysql database on phpmyadmin.
one of the tables in the database has a primary key field and I want to select a record from the database with a specific primary key. obviously this will only return 1 row however I am at a loss as to how I can run the query and then put the result into a single datarow object. all the da.fill overloads require a datset and while this is possible it feels inefficient to define a dataset and always reference it as:
dataset.tables("table").rows(0).item.....
when I could be using:
row.item.....
TL;DR, how can I populate a datarow with a dataadapter in vb.net?
I would suggest retrieving your data into the DataGridView control. To do this you can use the code I have inputted below from one of my projects.
Imports System.Data.SqlClient
Public Class Form1
Dim dbConnection As SqlConnection
Dim dbCommand As SqlCommand
Dim dbAdapter As SqlDataAdapter
Dim DataSet As New DataSet
Dim strSQL As String
Dim dbCount As String
Public Sub SQLConnect()
dbConnection = New SqlConnection("Data Source=connectionhere\sqlexpress;Initial Catalog=line_log;Integrated Security=True")
dbConnection.Open()
End Sub
Public Sub SQLCommand()
dbCommand = New SqlCommand(strSQL, dbConnection)
End Sub
Public Sub SQLAdapter()
dbAdapter = New SqlDataAdapter(strSQL, dbConnection)
End Sub
Public Sub SQLDisconnect()
dbConnection.Close()
End Sub
Public Sub DGVLoad()
Try
SQLConnect()
strSQL = "SELECT [item] FROM [table] WHERE ([item] = 'value')"
SQLAdapter()
DataSet.Clear()
dbAdapter.Fill(DataSet)
SQLDisconnect()
DataGridView1.DataSource = DataSet.Tables(0)
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
DGVLoad()
End Sub
I am building a small VB Application that queries a MSSQL Database and then displays those results in a Listbox. There is a TextBox (TextBox1) where the user will input a CharName that will be used to select the CharName in the database to return results for that user only. I currently have the sql query coded into Button1.
So what I am needing help with is taking the input from TextBox1 and replacing Chars.CharName in the sql query with the user supplied input so that when the button is clicked the query executes and populates ListBox1 with the results.
Btw I am a total noob with VB (clearly).
The code I have thus far is:
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub TextBox1_Text(sender As System.Object, e As System.EventArgs) Handles TextBox1.TextChanged
End Sub
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
Dim sqlquery As String
sqlquery = ("SELECT Chars.CharName, CharItems.Type, CharItems.TypeID, CharItems.ItemName, CharItems.Bag, CharItems.Slot, CharItems.ItemUID, CharItems.Craftname, CharItems.Gem1, CharItems.Gem2, CharItems.Gem3, CharItems.Gem4, CharItems.Gem5, CharItems.Gem6 FROM Chars INNER JOIN CharItems ON Chars.CharID = CharItems.CharID WHERE ([CharName] = '" + TextBox1.Text + "'")
End Sub
Private Sub ListBox1_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles ListBox1.SelectedIndexChanged
End Sub
End Class
you need to do your connection and fetch the results from your database and store them in a Datatable, then you can bind your Datatable to the ListBox
Not a VB guy so this is off the top of my head. Pay attention to the comments, though
'put these at the top of your code file:
imports System.Data.SqlClient
imports System.Data
'and this in the Button1_Click:
dim sql as string
dim cname as string
cname=TextBox1.Text
'never just directly accept the input from a textbox, etc, into an SQL query. Always use a parameter so prevent SQL Injection attacks.
sqlquery="SELECT Chars.CharName, CharItems.Type, CharItems.TypeID,CharItems.ItemName,CharItems.Bag, CharItems.Slot, CharItems.ItemUID, CharItems.Craftname, CharItems.Gem1, CharItems.Gem2, CharItems.Gem3, CharItems.Gem4, CharItems.Gem5, CharItems.Gem6 FROM Chars INNER JOIN CharItems ON Chars.CharID = CharItems.CharID WHERE Chars.CharName = #CharName"
using connection as SqlConnection = new SqlConnection(ConnectionString) 'substitute ConnectionString for the connection string to your database, where you get this from is beyond the scope of this code but it should be somewhere secure i.e app.config ConnectionStrings section
connection.Open()
using comm as SqlCommand = new SqlCommand(query,conn)
dim p as SqlParameter = new SqlParameter("CharName",cname)
comm.Parameters.Add(p)
dim rs as SqlDataReader = comm.ExecuteReader
dim dt as DataTable = new DataTable
dt.Fill(rs)
end using 'comm
end using 'conn
ListBox1.DisplayMember="CharName"
ListBox1.DataSource=dt
ListBox1.DataBind()
You don't need brackets around the string literals when setting the value of sqlquery and there is a typo in there as well.
It should just be
Dim sqlquery As String
sqlquery = "SELECT Chars.CharName, CharItems.Type, CharItems.TypeID, CharItems.ItemName, CharItems.Bag, CharItems.Slot, CharItems.ItemUID, CharItems.Craftname, CharItems.Gem1, CharItems.Gem2, CharItems.Gem3, CharItems.Gem4, CharItems.Gem5, CharItems.Gem6 FROM Chars INNER JOIN CharItems ON Chars.CharID = CharItems.CharID WHERE [CharName] = '" + TextBox1.Text + "'"
There is the whole issue of SQL Injection with this approach that I don't want to get into here, but you really should read up on executing Stored Procedures instead of raw SQL so that you can parameterise your inputs.
Can someone point me in the right direction? I have not been able to find documentation to help me build a vb api that can read from a SQL Server stored procedure. I currently have an api that works, I was able to test my controller and the methods (GET, POST, ) work. Please let me know how can I read from a .sql file.
The code below is in Calendar Model - Calendar.vb
Imports System.Data.SqlClient
Imports System.IO
Public Class Form1
Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
Dim sqlFile As String = "C:\temp\test.sql"
Dim sqlText = File.ReadAllText(sqlFile)
Dim connStr = "Server=.\SQLEXPRESS; Database=testing; Integrated Security=SSPI"
Dim conn = New SqlConnection(connStr)
Dim sqlCmd = New SqlCommand(sqlText, conn)
Try
conn.Open()
sqlCmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox("Something went wrong: " & ex.Message)
Finally
If conn.State = ConnectionState.Open Then
conn.Close()
End If
End Try
End Sub
End Class
If the test.sql execute a run of stored procedure and if it's return a table you can read as this :
Dim reader As SqlDataReader = sqlCmd.ExecuteReader()
While reader.Read()
Console.WriteLine("{0}", reader(0))
End While
If it's return one value use this
intValue =Convert.ToInt32(sqlCmd.ExecuteScalar())