I want to create a connection string and use it to all forms in my application, but is showing error.
My code below throws the error: "Object reference not set to an instance of an object"
Imports System.Data.SqlClient
Imports System.Data.OleDb
Module sqlserverconnectionstring
Public connsql As SqlConnection
Dim connstr As String
Public Sub sqlserverconnection()
Try
connstr = "Provider=SQLOLEDB.1; Data Source=" & My.Settings.sqlservername & ";Initial Catalog=" & My.Settings.sqlDBname & ";Password=" & My.Settings.sqlPswd & ";User ID=" & My.Settings.sqlUserName
connsql.Open()
Catch ex As Exception
MsgBox(ex.Message.ToString)
End Try
End Sub
Public Sub sqlserverdisconnectdatabase()
Try
connsql.Close()
Catch myerror As SqlClient.SqlException
End Try
End Sub
End Module
The connsql field is never initialized, so it is always null (Nothing in VB.NET).
You'll want this:
Sub Connect()
Try
Me.connstr = "Provider=SQLOLEDB.1; Data Source=" & My.Settings.sqlservername & ";Initial Catalog=" & My.Settings.sqlDBname & ";Password=" & My.Settings.sqlPswd & ";User ID=" & My.Settings.sqlUserName
Me.connsql = New SqlConnection( Me.connstr )
Me.connsql.Open()
Catch ex1 As InvalidOperationException
MsgBox( ex1.Message )
Catch ex2 As SqlException
MsgBox( ex2.Message )
Catch ex3 As ConfigurationErrorsException
MsgBox( ex3.Message )
End Try
End Sub
I note that it will be a better idea to store the entire connection string in your App.config file instead of building it at runtime (what if the user has an SSPI connection, for example?):
In your App.config file:
<configuration>
<connectionStrings>
<add name="db" connectionString="it goes here" />
</connectionStrings>
</configuration>
Usage:
Me.connsql = new SqlConnection( ConfigurationManager.ConnectionStrings("db").ConnectionString )
You need to create an object of the SqlConnection first, and set the connectionString befor opening the connection
connstr = "Provider=SQLOL ..."
connsql = new SqlConnection(connstr)
connsql.Open()
connstr = "Provider=SQLOLEDB.1; Data Source=" & My.Settings.sqlservername & ";Initial Catalog=" & My.Settings.sqlDBname & ";Password=" & My.Settings.sqlPswd & ";User ID=" & My.Settings.sqlUserName
connsql = New SqlConnection(connstr)
connsql.Open()
solved
Thanks to all.....
I have a readini file to connect to my SQL Server table, and in my query code to display data from it, I'm getting an error that I've not been able to solve, is there anybody here who can?
This is the error:
Error 1
Overload resolution failed because no accessible 'New' can be called with these arguments:
'Public Sub New(selectCommandText As String, selectConnection As System.Data.OleDb.OleDbConnection)': Value of type 'SQLServerApplication.readini' cannot be converted to 'System.Data.OleDb.OleDbConnection'.
'Public Sub New(selectCommandText As String, selectConnectionString As String)': Value of type 'SQLServerApplication.readini' cannot be converted to 'String'.
This is the code:
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class frmViewDtb
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim connection As readini = New readini()
connection.getConnectionString()
Dim sql As String = "SELECT * FROM tblPerson"
Dim da As New OleDbDataAdapter(sql, connection)
Dim ds As New DataSet()
da.Fill(ds, "tblPerson")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblPerson"
End Sub
End Class
The line that the error is occurring on is line 13:
Dim da As New OleDbDataAdapter(sql, connection)
Code for getConnectionString;
Public Function getConnectionString() As String
Dim s As String =
"Provider=" & provider & ";" &
"user ID=" & username & ";" &
"password=" & password & ";" &
"initial catalog=" & databasename & ";" &
"data source=" & servername & "; " &
"Persists Security Info=False"
End Function
Thanks in advance if you can get it!
I believe you are getting the error as the constructor for OleDbDataAdpater is expecting two strings and your connection variable isn't a string. I suspect your code needs to look like this:
Dim connection As readini = New readini()
Dim ConnString = connection.getConnectionString()
Dim sql As String = "SELECT * FROM tblPerson"
Dim da As New OleDbDataAdapter(sql, ConnString)
Dim ds As New DataSet()
da.Fill(ds, "tblPerson")
DataGridView1.DataSource = ds
DataGridView1.DataMember = "tblPerson"
The getConnectionString method also needed amending to add the Return statement:
Public Function getConnectionString() As String
Dim s As String =
"Provider=" & provider & ";" &
"user ID=" & username & ";" &
"password=" & password & ";" &
"initial catalog=" & databasename & ";" &
"data source=" & servername & "; " &
"Persists Security Info=False"
Return s
End Function
Within my MDIParent Me_Load I have an SQL query that returns user information based upon Windows ID. This works well, however I'd really like to move this logic out into perhaps a module and assign each value in the db to a global variable to be used elsewhere. I'd like to be able to access the contact_id in any child form of the parent MDI. I'm used to PHP where I'd just assign it to a session variable that I could reference anywhere.
This is my current SQL Code
Dim sql_query As String
Dim errorMessages As New StringBuilder()
Dim cnn = ConfigurationManager.ConnectionStrings("sql_connection_string").ConnectionString
Dim adapter As SqlDataAdapter
Dim ds As New DataTable()
Dim User_ID As String
Dim User_First_Name As String
Dim User_Last_Name As String
Dim User_Contact_CD As String
Dim User_Login As String
sql_query = "SELECT Contact_ID, First_Name_CH, Last_Name_CH, Contact_CD, Login_VC FROM [Worktool].[dbo].[vwEmployees_T] WHERE Login_VC = '" & username & "'"
Using connection As New SqlConnection(cnn)
Try
If connection.State = ConnectionState.Closed Then connection.Open()
adapter = New SqlDataAdapter(sql_query, connection)
adapter.Fill(ds)
User_ID = ds.Rows(0)("Contact_ID").ToString()
User_First_Name = ds.Rows(0)("First_Name_CH").ToString()
User_Last_Name = ds.Rows(0)("Last_Name_CH").ToString()
User_Contact_CD = ds.Rows(0)("Contact_CD").ToString()
User_Login = ds.Rows(0)("Login_VC").ToString()
connection.Close()
Catch ex As SqlException
MsgBox("Sorry, there was an issue with the connection. Please try again ! ")
Dim i As Integer
For i = 0 To ex.Errors.Count - 1
errorMessages.Append("Index #" & i.ToString() & ControlChars.NewLine _
& "Message: " & ex.Errors(i).Message & ControlChars.NewLine _
& "LineNumber: " & ex.Errors(i).LineNumber & ControlChars.NewLine _
& "Source: " & ex.Errors(i).Source & ControlChars.NewLine _
& "Procedure: " & ex.Errors(i).Procedure & ControlChars.NewLine)
Next i
MsgBox(errorMessages.ToString())
End Try
End Using
'Assign messages
main_window_welcome.Text = "Welcome back, " & Replace(User_First_Name, " ", "") & " " & Replace(User_Last_Name, " ", "")
variable username is
Public username = Environ$("Username")
You've declared the 4 variables in the class and they are private to that class. At this point your code works. Hilight those 4 variable declarations and Cut them. Your code shows errors because you just removed the declarations.
Add a module to your solution (name it what you want)
paste the declarations into the module body.
change the Dim to Public.
Your errors disappear.
Your variables are now public and available throughout your solution.
Please help advise I just started writing
I'm using SQL Server Management Studio 2012
Table name is dbo.info
Imports System.Data
Imports System.Data.SqlClient
Public Class Form1
Dim SQLCon As New SqlConnection("Data Source=SECURITY;Integrated Security=False;User ID=sa;Password=Rapoo;Connect Timeout=15;Encrypt=False;TrustServerCertificate=False")
Dim cmd As New SqlCommand
Private Sub btmSave_Click(sender As Object, e As EventArgs) Handles btmSave.Click
If txtStaff.Text <> "" And txtName.Text <> "" Then
SQLCon.Open()
cmd.CommandText = "insert into info (Club,Staff,Name,Age,Gender,Mobile,Mail,Remark) values ('" & lblClub.Text & "','" & txtStaff.Text & "','" & txtName.Text & "','" & txtAge.Text & "','" & txtGender.Text & "','" & txtMobile.Text & "','" & txtMail.Text & "','" & txtRemark.Text & "')"
cmd.ExecuteNonQuery()
SQLCon.Close()
End If
Clear()
End Sub
The error is
An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Invalid object name 'info'.
In your connection string is missing the part
Database=yourDatabaseName;
or
Initial Catalog=yourDatabaseName;
Without this key your query executes against the MASTER database where there is no INFO table
In the form load event, I connect to the SQL Server database:
Private Sub AddBook_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myConnection = New SqlConnection("server=.\SQLEXPRESS;uid=sa;pwd=123;database=CIEDC")
myConnection.Open()
End Sub
Here in the Insert event, I use the following code:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")")
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
And It produces the following error:
ExecuteNonQuery: Connection property has not been initialized
Connection Assignment - You aren't setting the connection property of the SQLCommand. You can do this without adding a line of code. This is the cause of your error.
myCommand = New SqlCommand("INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, EnterDate, CatID, RackID, Amount) VALUES('" & txtBookCode.Text & "','" & txtTitle.Text & "','" & txtAuthor.Text & "','" & txtPublishYear.Text & "','" & txtPrice.Text & "', #" & txtEnterDate.Text & "#, " & txtCategory.Text & "," & txtRack.Text & "," & txtAmount.Text & ")", MyConnection)
Connection Handling - You also need to remove `MyConnection.Open' from your Load Handler. Just open it and close it in your Click Handler, as you are currently doing. This is not causing the error.
Parameterized SQL - You need to utilize SQL Parameters, despite the fact that you are not using a Stored Procedure. This is not the cause of your error. As Conrad reminded me, your original code dumps values straight from the user into a SQL Statement. Malicious users will steal your data unless you use SQL Parameters.
Dim CMD As New SqlCommand("Select * from MyTable where BookID = #BookID")
CMD.Parameters.Add("#BookID", SqlDbType.Int).Value = CInt(TXT_BookdID.Text)
You need to set the Connection property on the command:
myCommand.Connection = myConnection
Pretty much what the error message implies - the Connection property of the SqlCommand object hasn't been assigned to the connection you opened (in this case you called it myConnection).
Also, a word of advice here. Do some reading on sql parameters - doing sql concatenation from user input without any sanity checks is the way SQL injection attacks happen.
This is one way to do it:
Private Sub cmdAdd_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmdAdd.Click
Try
myConnection.Open()
myCommand = New SqlCommand( _
"INSERT INTO tblBook(BookCode, BookTitle, Author, PublishingYear, Price, " & _
" EnterDate, CatID, RackID, Amount) " & _
"VALUES(#bookCode, #bookTitle, #author, #publishingYear, #price, #enterDate, " & _
" #catId, #rackId, #amount)")
myCommand.Connection = myConnection
with myCommand.Parameters
.AddWithValue("bookCode", txtBookCode.Text)
.AddWithValue("bookTitle", txtTitle.Text)
.AddWithValue("author", txtAuthor.Text)
.AddWithValue("publishingYear", txtPublishYear.Text)
.AddWithValue("price", txtPrice.Text)
.AddWithValue("enterDate", txtEnterDate.Text)
.AddWithValue("catId", txtCategory.Text)
.AddWithValue("rackId", txtRack.Text)
.AddWithValue("amount", txtAmount.Text)
end with
myCommand.ExecuteNonQuery()
MsgBox("The book named '" & txtTitle.Text & "' has been inseted successfully")
ClearBox()
Catch ex As Exception
MsgBox(ex.Message())
End Try
myConnection.Close()
End Sub
Module Module1
Public con As System.Data.SqlClient.SqlConnection
Public com As System.Data.SqlClient.SqlCommand
Public ds As System.Data.SqlClient.SqlDataReader
Dim sqlstr As String
Public Sub main()
con = New SqlConnection("Data Source=.....;Initial Catalog=.....;Integrated Security=True;")
con.Open()
frmopen.Show()
'sqlstr = "select * from name1"
'com = New SqlCommand(sqlstr, con)
Try
com.ExecuteNonQuery()
'MsgBox("success", MsgBoxStyle.Information)
Catch ex As Exception
MsgBox(ex.Message())
End Try
'con.Close()
'MsgBox("ok", MsgBoxStyle.Information, )
End Sub
End Module
Please try to wrap the use of your connections (including just opening) inside a USING block. Assuming the use of web.config for connection strings:
Dim connection As New SqlConnection(ConfigurationManager.ConnectionStrings("web.config_connectionstring").ConnectionString)
Dim query As New String = "select * from Table1"
Dim command as New SqlCommand(query, connection)
Using connection
connection.Open()
command.ExecuteNonQuery()
End Using
And PARAMETERIZE anything user-entered.. please!