Change sql server from visual basic form - vb.net

I want to let the users change the sql server connetion manually from a settings form because the application will be used in many company
i tried this:
i create a string in settings "sqlservername"
then in the loading form i put a textbox "txt_sqlservername" and savebutton
the button event
My.Settings.sqlservername = Me.txt_sqlservername.Text
My.Settings.Save()
MsgBox("Server Name Was Updated", MsgBoxStyle.Information, "Videos Database - New Server Name")
Me.Close()
and this is my connection string
Public SQLCon As New SqlConnection With {.ConnectionString = "Server=My.Settings.sqlservername;Database=Videos;User=sa;Pwd=123456;"}
when i open my main form nothing shown
any help?

You can give a form that asks for user input for the connection string and then save the connection string in the application settings.
You can use this connection string from the settings every time you define a connection in the application.

The string formatting is wrong where the connection is defined.Make correction like shown below:
Public SQLCon As New SqlConnection With {.ConnectionString = "Server=" & My.Settings.sqlservername & ";Database=Videos;User=sa;Pwd=123456;"}

Related

'Fill: SelectCommand.Connection property has not been initialized.'

I am using a visual studio 2022 vb.net and mssql management studio.
login form
Private Sub Btnlogin_Click(sender As Object, e As EventArgs) Handles Btnlogin.Click
cn.Open()
cm = New SqlClient.SqlCommand("select * from table_user where username like '" & username.Text & "' and password like '" & password.Text & "'and usertype= '" & usertype.SelectedItem & "'", cn)
dr = cm.ExecuteReader
sda.Fill(dt)
If (dt.Rows.Count > 0) Then
MessageBox.Show("You are login as " + dt.Rows(0)(2))
If (usertype.SelectedIndex = 0) Then
Dim a As New dashboard
a.Show()
Me.Hide()
Else
Dim b As New Admin
b.Show()
Me.Hide()
End If
Else
MessageBox.Show("Username or Password Incorrect. CONTACT ADMINISTRATOR!")
End If
cn.Close()
End Sub
Module
Imports System.Data.SqlClient
Module Module1
Public cn As New SqlConnection("Data Source=DESKTOP-7POF5HE\SQLEXPRESS;Initial Catalog=dict;Integrated Security=True")
Public cm As New SqlCommand
Public dr As SqlDataReader
Public sda As SqlDataAdapter = New SqlDataAdapter(cm)
Public dt As DataTable = New DataTable()
End Module
CAN YOU HELP ME TO SOLVE THIS?
Seems there are several issues with this code.
In your module, you create the command object and the data adapter object. But in the form method, you create a new command object. But that will not update the data adapter to use that new command object. Class variables are reference types. They just point to an object in the memory somewhere. Your cm variable will point to the new command object, but your sda object will internally still point to the old command object.
Furthermore:
You are using both a data reader and a data adapter. Both have their pros and cons, but you probably don't need (or want) to use them both at the same time. I assume you want to use the data adapter. So you can drop the dr = cm.ExecuteReader line in the form method.
Since you will probably always want to create command objects and data adapter objects on the fly (as I would), you could remove them from the module. Just create them both as local variables in your form method.
Try to use the Using statement for such objects. They need to be disposed of nicely when the form method finishes. Otherwise they might keep valuable system resources in use until the .NET garbage collector disposes them (which will probably occur when you close your application, not earlier).
Also be careful with concatenating SQL statements from variables. What would happen here if you enter this text in your username textbox?: ';delete from table_user;--
Hint: Do not actually try it! It will try to delete all your users from the database table table_user. Just try to manually reproduce the SQL string that will be built in your form method. This is called an SQL injection attack. To avoid such nasty things, it's easiest to use SQL parameters in your SQL statements and pass them separately to your command object.

Problems with DataAdapter at VB.Net in a connection to SQL Server 2008

I´m experimenting troubles on a local connection to SQL Server 2008, it´s throwing me the next especific error:
A network-related or instance-specific error ocurred while establishing a connection to SQL Server. The server was not found or was not accesible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections (error 40)
I´ve tried with most of solutions concerning to SQL Services and Firewall Solutions, so i think the problem is specific in the source code, so it is:
Private Sub cargar_Combo(ByVal ComboBox As ComboBox, ByVal sql As String)
Dim strConexion As String = "Data Source=Angel-PC\SQLEXPRESS1;Initial Catalog=sistemaReferencias;Integrated Security=True"
Dim conexion As New SqlConnection(strConexion)
Try
conexion.Open()
Dim cmd As New SqlCommand(sql, conexion)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet
da.Fill(ds)
ComboBox.DataSource = ds.Tables(0)
ComboBox.DisplayMember = ds.Tables(0).Columns(1).Caption.ToString
ComboBox.ValueMember = ds.Tables(0).Columns(0).Caption
Catch ex As Exception
MessageBox.Show(ex.Message.ToString, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
Finally
If conexion.State = ConnectionState.Open Then
conexion.Close()
End If
End Try
End Sub
I know that the String connection is right, because i used it in another method, the error comes specifically at the "da.Fill(ds)" line, those are the basics
I really appreciate any help you can provide.
Go to your desktop. Right click and add a new text file, "test.txt".
Rename the text file to test.udl, you will get a warning, just accept it.
Double click test.udl, and you will have an interactive dialog to configure your connection string.
Once you have configured the connection string. Click save. The right click the test.udl file and open in notepad. This will give you the connection string that you need to put into your app.

Vb.net 2010 Connection to SQL Server 2008

I am trying to connection to MS SQL SERVER 2008 database (students), i want to make sure:
1) If connection string that i made is OK
Dim connectionString As New SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
2) How can i check if dataset is producing any results?
Code:
Public Class Form1
'Connection String + DataAdaptor + DataSet
'Declared Outside Any Subroutines/Functions
Dim connectionString As New SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
Dim dataAdaptor As New SqlDataAdapter()
Dim objdataSet As New DataSet()
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
dataAdaptor.SelectCommand = New SqlCommand()
dataAdaptor.SelectCommand.Connection = connectionString
dataAdaptor.SelectCommand.CommandText = "select * from basic_info;"
dataAdaptor.SelectCommand.CommandType = CommandType.Text
connectionString.Open()
dataAdaptor.Fill(objdataSet, "StudentInfo")
connectionString.Close()
grd.AutoGenerateColumns = True
grd.DataSource = objdataSet
grd.DataMember = "basic_info"
dataAdaptor = Nothing
connectionString = Nothing
End Sub
About your first question, If connection string that i made is OK
If you did not get any exceptions, you've successfully made the connection to your database.
About your second question.
There are two things you can do.
Debug the wrong way. (It works though)
MsgBox(objdataSet.Tables[0].Rows.Count);
Learn and debug the correct way.
Read these articles
Debugging Basics
Visual Studio Debugging
Debugging Basics: Breakpoints
Anyway, learn how to use the debugger properly, put a break point, analyse the objdataSet object in a watch window and see if any results are present.
1) If connection string that i made is OK
Easy way to verify connection strings is to connect using the "Server Explorer" in Visual Studio. Once you get a good connection, right-click on the connection and just grab the "Connection String" property.
2) How can i check if dataset is producing any results?
MsgBox(objdataSet.GetXML)
GetXML will return ALL the data in the dataset in XML format.
Also, don't globally declare variables if you don't need to.
Declare them closer, or not at all, like so...
Dim objdataSet As New Data.DataSet()
Using connectionString As New Data.SqlClient.SqlConnection("server=X86ONX64; database=students; Integrated Security=True")
With New Data.SqlClient.SqlDataAdapter()
.SelectCommand = connectionString.CreateCommand
.SelectCommand.CommandText = "select * from basic_info;"
.SelectCommand.CommandType = Data.CommandType.Text
.Fill(objdataSet, "StudentInfo")
End With
MsgBox(objdataSet.GetXML)
End Using
'Now put it in your dataset...'
Hope this helps.

how to keep a odbc connection open in vb.net

I'm trying to connect to a database and keep the connection open for any amount of user activity/queries within the database. Currently I have a connection that opens and closes for any query (save, update, etc...) which requires the logon process to the back-end every time the user saves etc... Is there a way to simply connect and leave the connection open so there won't be a lag time when running the query due to the logon process? This is what I'm using:
Private sConStrFormat As String = "Provider=TDOLEDB;Data Source=TDDEV;Persist Security Info=True;User ID={0};Password={1};Default Database=bcpm_ddbo;Session Mode=ANSI;"
Private Sub cmdsave_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdsave.Click
Dim sSQL As String
Dim sConStr As String
Dim user As String
Dim pass As String
user = txtuser.Text
pass = txtpass.Text
Dim UserName As String = user
Dim Password As String = pass
sConStr = String.Format(sConStrFormat, UserName, Password)
Using Con As System.Data.OleDb.OleDbConnection = New System.Data.OleDb.OleDbConnection(sConStr)
Con.Open()
sSQL = "INSERT INTO LTC_FBS (CLM_NUM) VALUES ('" & Me.txtClaim.Text & "')"
Dim cmdins As New System.Data.OleDb.OleDbCommand(sSQL, Con)
cmdins.ExecuteNonQuery()
Con.Close()
End Using
End Sub
.Net automatically maintains a connection pool for you. According to MSDN, when you call Close() on the Connection the framework
releases the connection to the
connection pool, or closes the
connection if connection pooling is
disabled
In vb.net 4.5 do the following:
At the top straight after the class definer put in this line:
Public Shared conn As OdbcConnection
Then, in the subs where you want to use the connection use this line:
If conn Is Nothing Then conn = New OdbcConnection(<your_connection_string>): conn.Open()
Then the New OdbcCommand will use the existing connection without opening a new one. Don't close the connection in your script until you are quite certain you're finished with it (_Shutdown is a good spot and you're good to go.
This also solves problems with MySQL when constantly opening new connections causes the max connections error.
Instead of defining 'con' in the using statement, define it up above as a static variable. When the function is called, you can see if 'Con' has been assined or not. If not, you build your connection string and set Con = New OleDBConnection, and open it. Since it's a static variable, it will retain its value at the next call. Check that it's not nothing, and then use it right away. Make sure you don't call close in the routine or the connection will not remain open.

vb.net - sharing mdb access connection among multiple forms

I'm starting to put in a database into my application, however I'm drawing a blank on how to share a database connection among the dozen or so different forms in my MDI application. I'm assuming this has to do with interfaces or something but I can't find any relevant examples anywhere. Can someone help me out? Ideally what I'd like is when the app is loaded up there is a call to a function in the forms loading area which establishes a single connection to the mdb, that I can then call via any form so I don't always have to open/close connections everytime I need to update the db (assuming what I'm suggesting is better for overhead), unless that is a better option?
Here's a basic example of the mdb database access code I've got working:
Dim dt As DataTable = New DataTable()
Dim OleDbTran As OleDbTransaction = Nothing
Using connJET As OleDbConnection = New OleDbConnection("connection string here...")
Try
connJET.Open()
Dim sqlCount As OleDbCommand = New OleDbCommand("select * from mytable", connJET)
Using aReader As OleDbDataReader = sqlCount.ExecuteReader()
dt.Load(aReader)
End Using
If (dt.Rows.Count > 0) Then
MsgBox(dt.Rows.Count)
End If
OleDbTran = connJET.BeginTransaction()
Dim aCommand As OleDbCommand = connJET.CreateCommand()
aCommand.CommandText = "INSERT INTO Programs (title) VALUES (#title)"
aCommand.Transaction = OleDbTran
aCommand.Parameters.Add("#title", OleDbType.VarChar)
aCommand.Parameters("#title").Value = "Test"
aCommand.ExecuteNonQuery()
OleDbTran.Commit()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Using
Assuming that you create the connection in your startup form, then you could just add constructors to the other forms that accept a SqlConnection and send that in whenever you create an instance of that form.
Or if you prefer, you create something like this:
Public Class Connection
Private Shared connection As OleDb.OleDbConnection
Public Shared ReadOnly Property Instance As OleDb.OleDbConnection
Get
If connection Is Nothing Then
connection = New OleDb.OleDbConnection("connstring")
End If
Return connection
End Get
End Property
End Class
And then you could access it by just calling Connection.Instance whenever you need it.