Connect to a database with visual basic - vb.net

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

Related

Getting DATA from SQL Server by WCF Services using ADO.NET VB.NET

I have attached WCF service to my sample website.
WCF functions work fine except one which use SQL query to get data from SQL server.
I'm not very familiar with VB.NET, my experience comes from VBA, it's similar but setting query is quite different.
At first I tried to use SqlDataReader then SqlDataAdapter - The same results. My Service has stuck.
Visual Studio shows error that SQL Server can't pass data because there is an internal error.
This is strange because when I use "WCF Test Client" in Visual Studio, then both functions work good and receive correct data. Also when I have attached this functions directly to my website also worked good. The problem is using them by WCF.
Below is my function with SQLDataAdapter
Public Function GetCookiesPriceDS(ByVal nameOfCookie As String) _
As DataSet Implements IService1.GetCookiesPriceDS
Dim queryString As String
Dim dataSet As DataSet = New DataSet("temporary")
queryString = "select CookiesPrice from " &
"tblCookies where CookiesName='" & nameOfCookie & "'"
Using connection As New SqlConnection _
("Server= xyz\SQLEXPRESS; Database = Cookies2; " &
"Integrated Security = true;User Id = xyz;Password = xyz")
Dim adapter As New SqlDataAdapter()
adapter.SelectCommand = New SqlCommand(queryString, connection)
adapter.Fill(dataSet)
Return dataSet
End Using
End Function
Ok, I have found some sample code in vb.net and have done some small changes. It doesn't work because in "WCF Test Client" red symbol appears next to function, with comment - "This operation is not supported in WCF Test Client because it uses type WcfService.CookiesData" But despite that I think this code is much better than my previous version and has better definition in and . But still there is some problem and I can't figure out what is wrong
Imports System.Data.SqlClient
Imports System.Data
Imports System.Configuration
Imports System.ServiceModel
Imports System.Runtime.Serialization
Public Class Service1
Implements IService1
Public Function GetCookiesPriceDS(ByVal nameOfCookie As String) _
As CookiesData Implements IService1.GetCookiesPriceDS
Using con As New SqlConnection("Server= xyz\SQLEXPRESS; Database = Cookies2; " &
"Integrated Security = true;")
Using cmd As New SqlCommand("select CookiesPrice from tblCookies where CookiesName='" & nameOfCookie & "'")
Using sda As New SqlDataAdapter()
cmd.Connection = con
sda.SelectCommand = cmd
Using dt As New DataTable()
Dim ck As New CookiesData()
sda.Fill(ck.CustomersTable)
Return ck
End Using
End Using
End Using
End Using
End Function
End Class
<ServiceContract()>
Public Interface IService1
<OperationContract()>
Function GetCookiesPriceDS(ByVal nameOfCookie As String) As CookiesData
End Interface
<DataContract()>
Public Class CookiesData
Public Sub New()
CustomersTable = New DataTable("TblCookies")
End Sub
<DataMember()>
Public Property CustomersTable() As DataTable
End Class

Microsoft.SqlServerCe.Client vs System.Data.SqlServerCe

I am writing a vb application that uses tableadapters.
I want to use the connection property of the tableadapters.
I have the following code:
Imports System.Data.SqlServerCe
Dim tbladaptBirds as TestBirdDBDataSetTableAdapters.tblBirdsTableAdapter
Dim tbladptrVetLinks As New TestBirdDBDataSetTableAdapters.tblVetLinksTableAdapter
Dim tbladptrVets As New TestBirdDBDataSetTableAdapters.tblVetsTableAdapter
Dim con As New SqlCeConnection
tbladaptBirds.Connection = con
This gives me the following error:
Value of type 'System.Data.SqlServerCe.SqlCeConnection' cannot be converted to 'Microsoft.SqlServerCe.Client.SqlCeConnection'.
When I replaced Imports System.Data.SqlServerCe with Imports Microsoft.SqlServerCe.Client, the error went away.
I was just playing around with a new project, and I typed in the following code
Imports System.Data.SqlServerCe
Dim con As New SqlCeConnection
Dim tbladptr As New DatasetTestDataSetTableAdapters.tblInfoTableAdapter
tbladptr.Connection = con ' no error
Why do I need Imports Microsoft.SqlServerCe.Client in the application I am writing while Imports System.Data.SqlServerCe is what I need in the application I was playing around with?
Thanks

import the data in xls file and open them without Microsoft Excel

I need to perform an application that cath values from SQL database after the esecution of a query. I must import the data in xls file and open them without Microsoft Excel. I'm a beginner and have too many problem. Can anyone help me.
This is my code, at the moment:
Option Infer On
Imports System.Linq
Imports System.Data.SqlClient
Imports System
Imports System.IO
Imports System.Drawing
Imports System.Drawing.Printing
Imports System.Windows.Forms
Imports ExcelLibrary.SpreadSheet
Public Class frmLottiCaricati
Dim CnSql As SqlConnection
Private Sub frmLottiCaricati_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
Me.MdiParent = Inizio
'TB_MinusValenza.Text = VariazionePrezzi.MinusValenza
'TB_Periodo.Text = VariazionePrezzi.Periodo
'DG_Prodotti.AutoGenerateColumns = False
Try
Dim StringaSql = "Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=" + Inizio.DatabaseSql + ";Data Source=" + Inizio.ServerSql + ";User ID=" + Inizio.UtenteSql + ";Password=" + Inizio.PwdSql
CnSql = New SqlConnection(StringaSql)
CnSql.Open()
Dim command As SqlCommand
Dim dadapter As New SqlDataAdapter
Dim DS_Prodotti As New Data.DataSet
Dim qry_Prodotti = "SELECT sistemaf.prodscadenze.Ministeriale, sistemaf.prodscadenze.Lotto, sistemaf.prodscadenze.Scadenza " & _
"FROM sistemaf.Prodscadenze "
'INNER JOIN sistemaf.Prodscadenze ON sistemaf.prodbase.Cod39 = sistemaf.prodscadenze.Ministeriale ;"
command = New SqlCommand(qry_Prodotti, CnSql)
dadapter.SelectCommand = command
dadapter.Fill(DS_Prodotti)
DG_Prodotti.DataSource = DS_Prodotti.Tables(0)
'DG_Prodotti.Columns("Descrizione").Width = 220
'DG_Prodotti.Columns("Ministeriale").Width = 60
DG_Prodotti.Columns("Lotto").Width = 60
'DG_Prodotti.Columns("Descrizione").AutoSizeMode = DataGridViewAutoSizeColumnMode.AllCells
'DG_Prodotti.Columns("Totale").DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
End Class
I can open the data only with Microsoft Excel now. Have any suggestions?
Use OpenXML to read the data from the Excel file without having Excel installed....
http://www.microsoft.com/en-gb/download/details.aspx?id=30425
Install that, then take a look at this site.
http://msdn.microsoft.com/en-us/library/office/gg575571%28v=office.15%29.aspx

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

vb.net create connection class

I want to create a class in vb.net that make the connection to database.
Also I need the way to use this class inside forms.
I need a code example of both the class and the form call
Thanks.
Right Click on your project in solution explorer > Add > Class then right the following. Change as per your requirements.
Imports System.Data.OleDb
Imports System.Data.OleDb.OleDbPermission
Imports System.Math
Public Class ClassCon
Dim Filepath As String = Application.StartupPath & "\yourDatabase.mdb;"
Public constring As String = "Provider=Microsoft.Jet.OLEDB.4.0;Persist Security Info=False;Jet OLEDB:Database Password=yourPassword;data source=" & Filepath
Public con As New OleDbConnection(constring)
Now use the connection class in form as below
Imports System.Data.OleDb
Public Class form1
Dim cmd As New OleDbCommand
Dim objcon As New ClassCon
If (objcon.con.State = ConnectionState.Closed) Then objcon.con.Open()
cmd100 = New OleDbCommand("INSERT INTO Mosey VALUES('" & TextBox1.Text & "')", objcon.con)
cmd.ExecuteNonQuery()
objcon.con.Close()
I am not an expert but my suggestion is you should, rather you must know what you are trying to search in Google. I am always able to find what I am looking for. And if you are still not sure then post here with your code i.e what you have tried so far.
All these code above are not tested with IDE so there may be typo.