Declaring a connection string in console application - vb.net

I am creating a console app and I have a connection string in the app.config file. When I try to reference this in my code I get an error on the configuration manager (ie its underlined).
Public Function getTPLvalue() As String
Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("GasNominationsConnectionString").ConnectionString)
conn.Open()
Dim cmd As New SqlCommand("select tpl from JADhist where dateSubmitted = (select MAX(datesubmitted) from JADhist)", conn)
Dim TPL As String = (cmd.ExecuteScalar())
conn.Close()
Return TPL
End Function
any ideas

You have to reference the namespace System.Configuration using:
Imports System.Configuration;

Related

Load Records using the ADODB Connection with Datagridview

So i have here my codes for fetching informations from the database using
the listview, and now i want to use the datagridview but i dont know how
to do it using the ADODB Connectionenter image description here.
If you are able to use an Odbc connection instead try this to retreive your data
Dim conn As New OleDb.OleDbConnection("path to your database")
Dim cmd As New OleDb.OleDbCommand
Dim da As New OleDb.OleDbDataAdapter
Dim sql as String
Sql = "your SQL Query"
conn.Open()
cmd.Connection = conn
cmd.CommandText = Sql
da.SelectCommand = cmd
You can try using Odbc Connection in VB.Net.
First add new Module named Connection.vb
Imports System.Data.Odbc
Module Connection
Public Con As New OdbcConnection
Public Adpt As New OdbcDataAdapter
Public Ds As New DataSet
Public Cmd As OdbcCommand
Public Read As OdbcDataReader
Public Sql As String
Public StrCon As String = "Dsn=Your DSN Name in Odbc Connector"
Public Sub Connect()
Con = New OdbcConnection(StrCon)
If Con.State <> ConnectionState.Closed Then Con.Close()
Con.Open()
End Sub
End Module
And next don't forget to add Imports System.Data.Odbc in every form you have to connect to your Odbc Connection.
Simple Code to add item on ComboBox from Database.
Call Connect()
Cmd = New OdbcCommand("SELECT * FROM `category` ", Con)
cmbKategori.Items.Clear()
cmbKategori.AutoCompleteCustomSource.Clear()
Read = Cmd.ExecuteReader()
If Read.HasRows = True Then
While Read.Read()
cmbKategori.AutoCompleteCustomSource.Add(Read("name_category"))
cmbKategori.Items.Add(Read("name_category"))
End While
End If

Connect to a database with visual basic

I am trying to connect an database, but it crash and it say that there are a
Connection problem, i have tryed this code in other pc, but now does not work
the error is:
There was a network or instance-specific error while trying to establish a connection to SQL Server. The server was not found or is not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections.
the code is this:
Module Module1
'FUNZIONE PER LA CONNESSIONE AL DATABASE
Public Function Connetti(ByVal sql As String, ByVal namedset As String, ByRef dataSet As DataSet)
Dim myConnString As String = "Persist Security Info=False;database=test;server=95.134.229.235;user id=web;pwd=fiautoppzione" 'server=Server206 'user id=utente_std;pwd=145111
Dim myConnection As New SqlConnection(myConnString)
Dim myInsertQuery As String = sql
Dim myCommand As New SqlCommand(myInsertQuery)
Dim myada As New SqlDataAdapter
Dim mydset As New DataSet(namedset)
Dim mydbs As New BindingSource
'IO.File.AppendAllText("C:\aggiorna.txt", sql & vbCrLf)
myCommand.Connection = myConnection
myada.SelectCommand = myCommand
myada.MissingSchemaAction = MissingSchemaAction.AddWithKey
mydset.EnforceConstraints = False
mydset.Clear()
myada.Fill(mydset, namedset)
mydbs.DataSource = mydset.Tables(namedset)
If Mid(sql, 1, 6) = "update" Then
mydset.Clear()
myada.Fill(mydset, namedset)
mydbs.DataSource = mydset.Tables(namedset)
End If
myConnection.Open()
dataSet = mydset
myCommand.Connection.Close()
Return mydbs
End Function
and the first part of the code:
Option Explicit On
Imports System.Data
Imports System.Data.Odbc
Imports System.Xml.Xsl
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Imports FIAppStabilimento.MySql.Data
Imports System.Data.SqlClient
Namespace MySql.Data.MySqlClient
End Namespace
For mySQL connection, you must not use the sqldataconnection.
First download MySql Connector/Net
Then add the following reference:
MySQL.Data
Sometimes MySql for somehow is not listed under .NET tab. Go to Browse tab, and navigate to the following path:
C:\Program Files (x86)\MySQL\MySQL Connector Net 6.6.4\Assemblies\v2.0
or C:\Program Files (x86)\MySQL\MySQL Connector Net 6.6.4\Assemblies\v4.0
and add MySql.Data.dll
Add the following code before Public Class Form1
MYSQL.dll Reference Image
Imports MySql.Data.MySqlClient
Then add the following declaration below Public Class Form1
Dim conn As New MySqlConnection
Public Sub connect()
Dim DatabaseName As String = "test"
Dim server As String = "95.134.229.235"
Dim userName As String = "web"
Dim password As String = "fiautoppzione"
If Not conn Is Nothing Then conn.Close()
conn.ConnectionString = String.Format("server={0}; user id={1}; password={2}; database={3}; pooling=false", server, userName, password, DatabaseName)
Try
conn.Open()
MsgBox("Connected")
Catch ex As Exception
MsgBox(ex.Message)
End Try
conn.Close()
End Sub

Connection string issue in VB.NET?

I have the following connection string class
Imports System.Data.SqlClient
Public Class DBConnection
Sub GetConnection()
Dim CrmsConn As New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("crmsConnectionString").ConnectionString)
End Sub
End Class
And I have tried to call the connection string from the above class as follows:
Dim dbcon As DBConnection
Dim con As New SqlConnection(dbcon.GetConnection())
But it has an error near dbcon.GetConnection().
What is the solution?
GetConnection is a sub. This means that it doesn't return anything and you cannot try to use an inexistant return value. (This is a compile time error, you can't produce any executable code until you fix it)
Make it a function and public
Public Function GetConnection() as SqlConnection
return New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("crmsConnectionString").ConnectionString)
End Function
and then use it as (but create the class instance first otherwise a null reference exception occurs at runtime)
' Create the instance of the DBConnection class and ...
Dim dbcon As DBConnection = new DBConnection()
' ... get the connection
Dim con as SqlConnection = dbcon.GetConnection()
Finally remember to use the Using statement around disposable objects like this
Using con = dbCon.GetConnection()
....
End Using

Declaration Expected

Good day all. Please advise me
Why I got an error message "Declaration Expected" when put the cursor on cmd variable. What Should I do?! .. the code appears below:
Imports System.Data.Sqlclient
Imports System.Configuration
Partial Class _Default
Inherits Page
Private Shared Connectionstr As String ="DataSource=localhost;initialCatalog=Orders;Integrated Security=true"
Dim conn As SqlConnection = New SqlConnection(Connectionstr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText="SELECT * FROM dbo.Customers"
End Class
You are attempting to use the variable command outside a Property, Function, or Method. At the very least, try wrapping your command in a method (Sub) which performs the desired action with the data:
Partial Class _Default
Inherits Page
Private Sub DoSomethingWithCustomers()
Dim conn As SqlConnection = New SqlConnection(Connectionstr)
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = "SELECT * FROM dbo.Customers"
conn.Open()
Dim dr = cmd.ExecuteReader()
' Do something with the data returned . . .
' ...
' Now Cleanup:
conn.Close()
cmd.Dispose()
conn.Dispose()
End Sub
The above can be improved by wrapping your data access objects in Using blocks, which handle proper disposal of unmanaged resources for you:
Private Sub DoSomethingBetterWithCustomers()
Dim SQL As String = "SELECT * FROM dbo.Customers"
Using conn As New SqlConnection(Connectionstr)
Using cmd As New SqlCommand(SQL, conn)
conn.Open()
Dim dr = cmd.ExecuteReader()
' Do something with the data returned
' . . .
dr.Close()
End Using ' Using Block takes carre of Disposing SqlCommand
End Using ' Using Block takes care of Closing and Disposing Connection
End Sub
Beyond that, it is difficult to know what, precisely, you are trying to do with your code, so the two examples above are really, really basic and general.

VB.NET connection to MS Access

I get an error when I am trying to connect to a Microsoft Access DB using VB.NET. I see examples all over the web. My code looks like those examples, however I am getting a build error message stating:
Type 'System.Data.OleDb.OleDbConnection' is not defined.
I have tried adding some kind of import statement for the system.data.oledb... but that does not seem to work. My code is below. It is a basic connection so I am thinking that I am missing some kind of add in, library, or setting. Any and all help would be greatly appreciated.
Public Function TestMain(ByVal args() As Object) As Object
' Connection String to MS Access DB
Dim connectStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=C:\Users\DMalerman\keyword.accdb;" & _
"Persist Security Info=False;"
MsgBox(connectStr)
' Create connection to the db
Using connection As New System.Data.OleDb.OleDbConnection(connectStr)
' Create the SQL Query
Dim readQuery As String = "Select KeywordDriver.ScriptName from KeywordDriver " & _
"where KeywordDriver.Keyword = test"
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
'Open the Connection
connection.Open()
' Query the Database
Dim dbReader As System.Data.OleDb.OleDbDataReader = queryCommand.ExecuteReader()
' Loop until there is nothing left to read
While dbReader.Read()
Dim sKeyword As String = ""
sKeyword = dbReader.GetString(0)
MsgBox(sKeyword)
End While
' Close the Reader
dbReader.Close()
End Using
Return Nothing
End Function
did you try
imports System.Data.OleDb
?
if so, did it give you an error?
Please try to modify this line:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery, connection)
by putting these only:
Dim queryCommand As New System.Data.OleDb.OleDbCommand(readQuery)
queryCommand.Connection = connection
Imports System.Data
Imports System.Data.OleDb
Module Module1
Public str As String
Public con As OleDbConnection
Public cmd As OleDbCommand
Public dtreader As OleDbDataReader
Public dtadapter As OleDbDataAdapter
Public Sub openconn()
str = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|\Database2.mdb"
con = New OleDbConnection(str)
Try
con.Open()
Catch ex As Exception
MessageBox.Show("gagal koneksi")
End Try
End Sub
End Module