VB.net connection string to sql database - vb.net

After using the following code no errors are shown, but my database is not updated once I have made a change using my management system application.
Any recommendations ?
Dim constring As String = Application.StartupPath.ToString() + "\mydatabaseName.mdf"
Public c As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=" + constring + ";Integrated Security=True;User Instance=True"
Sub openConnection()
conn.ConnectionString = c
conn.Open()
End Sub

Use the following code:
Dim constring As String = Application.StartupPath.ToString() + "\mydatabaseName.mdf"
Public c As String = "Data Source=.\SQLEXPRESS;AttachDbFilename=" + constring + ";Integrated Security=True;User Instance=True"
Dim conn As New SqlConnection(c)
Dim comm As New SqlCommand
Dim strQuery As New String = "SQL Update Query"
Try
comm.CommandText = strQuery
comm.Connection = conn
conn.Open()
comm.ExecuteNonQuery()
Catch ex As Exception
End Try
Change your connection string to:
"Data Source=.\SQLEXPRESS;AttachDbFilename=" + constring + ";Initial Catalog=mydatabaseName;Integrated Security=True;User Instance=True"
Using InitialCatalog helps when there are more than one databases.

Related

Best way to deal with Open Datareader Error (vb.net and mysql)

My Project running on VS 2013 & MySQL, I have declared public variable conn as mysqlconnection and I use the same connection all over the project to perform any database operation.
Public conn As New MySqlConnection
Public Sub createConnection()
If conn.State = ConnectionState.Closed Then
conn.ConnectionString = parseConfigXML()
conn.Open()
End If
End Sub
Public Function parseConfigXML()
Try
Dim m_xmld As XmlDocument
Dim m_nodelist As XmlNodeList
Dim m_node As XmlNode
m_xmld = New XmlDocument()
m_xmld.Load("../../../appconfig.xml")
m_nodelist = m_xmld.SelectNodes("/app/config")
Dim hostname, dbname, dbuser, dbpassword As String
hostname = ""
dbname = ""
dbuser = ""
dbpassword = ""
For Each m_node In m_nodelist
hostname = m_node.ChildNodes.Item(0).InnerText.ToString
dbname = m_node.ChildNodes.Item(1).InnerText.ToString
dbuser = m_node.ChildNodes.Item(2).InnerText.ToString
dbpassword = m_node.ChildNodes.Item(3).InnerText.ToString
Next
Dim connectionString = "Database=" & dbname & "; Data Source=" & hostname & "; User Id=" & dbuser & ";Password=" & dbpassword & "; Character Set=utf8"
Return connectionString
Catch errorVariable As Exception
MsgBox("Oops, An error occured: " & errorVariable.ToString)
End Try
End Function
Whenever connection is required, I use it as follows:
Try
Dim query As String = "select * from tbl_lang where lang_status=1"
Dim cmd As New MySqlCommand(query, conn)
Dim dr As MySqlDataReader
dr = cmd.ExecuteReader
If dr.HasRows Then
Do While dr.Read
cmb.Items.Add(dr.GetString("lang_name"))
Loop
End If
cmb.SelectedItem = "English"
If Not dr.IsClosed Then dr.Close()
Catch ex As Exception
lbl_error.text="Oops, An error occured: " & ex.ToString
End Try
I always have this issue when the code is reused: There is already open datareader for this connection.
What is the best way to deal with it? someone had mentioned to use open new connection for every query and then close it. Somehow, I am not convinced with it as it may create performance issues.
Please suggest the best way to overcome the issue.

Load Report failed with crystal report

I got an error (load report failed) when trying to print crystal report in my vb.net application
but my problem is (this error hasn't occurred always) maybe after printing unknown number of reports, then once this error has occurred.
Here is my code:
Dim cmd As New OleDbCommand
Dim connp As New OleDbConnection
Dim da As New OleDbDataAdapter
Dim ds As New DataSet
Dim strsql As String
Dim strreprotname As String
Try
connp.ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & Application.StartupPath & "\report.mdb; Jet OLEDB:Database Password=KNOZ1003"
connp.Open()
ds.Reset()
strsql = "select * from tab3"
cmd.CommandText = strsql
cmd.Connection = connp
da.SelectCommand = cmd
da.Fill(ds)
strreprotname = "cashrpt"
Dim strreportpath As String = Application.StartupPath & "\Reports\" & strreprotname & ".rpt"
Dim rptdocument As New CrystalDecisions.CrystalReports.Engine.ReportDocument
Dim prnset As New Printing.PrinterSettings
Dim pg As New Printing.PageSettings
rptdocument.Load(strreportpath)
rptdocument.SetDataSource(ds.Tables(0))
rptdocument.SetDatabaseLogon("", "", "", Application.StartupPath + "\report.mdb")
prnset.PrinterName = cashprinter
rptdocument.PrintToPrinter(prnset, pg, False)
cmd.Dispose()
connp.Close()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try

VB.NET - Key word is not supported: provider

When I try to connect to AcessDB, I get the error
"Keyword is not supported: provider".
When I try to change provider, I get another error. When I delete provider tag, I also get an error.
Dim Exists As Boolean = False
Dim ConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Name\Documents\Visual Studio 2010\Projects\datagrid\datagrid\pokus.accdb;Persist Security Info=False;"
Dim connection As New SqlConnection(ConnectionString)
Try
connection.Open()
Dim command As SqlCommand = connection.CreateCommand
command.CommandText = "SELECT * FROM studenti"
Dim reader As SqlDataReader = command.ExecuteReader
If reader.HasRows Then
Exists = True
Else
Exists = False
End If
reader.Close()
command.Dispose()
Catch ex As Exception
Console.Write(ex.Message)
Finally
connection.Close()
End Try
SqlConnection, SqlCommand, etc. are SQL Server-specific classes. You can't use them to connect to MS Access.
The documentation for SqlConnection makes this very clear:
Represents an open connection to a SQL Server database.
Consider using the OldDbConnection and related classes instead.
I always write wrapper classes for database connections, and I always recommend the same.
Dim sConnectionString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Name\Documents\Visual Studio 2010\Projects\datagrid\datagrid\pokus.accdb;Persist Security Info=False;"
Dim Conn As New OleDbConnection
Conn.ConnectionString = sConnectionString
Conn.Open()
Dim sQuery As String = "SELECT * FROM studenti"
Dim da As New OleDbDataAdapter(sQuery, Conn)
Dim dt As New DataTable
da.Fill(dt)
Conn.Close()

VB link SQL server problems

I received a error as following:
Conversion from type 'SqlConnection' to type 'String' is not valid.
My VB coding is :
Dim conn As New SqlConnection
Dim cmd As New SqlCommand
Dim da As New SqlDataAdapter
Dim dt As New DataTable
Dim sSQL As String = String.Empty
Try
conn = New SqlConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = "SELECT * FROM HostTable"
If Me.cboSearchBy.Text = "Name" Then
sSQL = sSQL & " where HOSTNAME like '%" & Me.txtSearch.Text & "%'"
ElseIf Me.cboSearchBy.Text = "Function" Then
sSQL = sSQL & " where FUCTION like '%" & Me.txtSearch.Text & "%'"
End If
cmd.CommandText = sSQL
da.SelectCommand = cmd
da.Fill(dt)
Me.dtgResult.DataSource = dt
If dt.Rows.Count = 0 Then
MsgBox("No record found!")
End If
Function Get_Constring()
If Microsoft.VisualBasic.Right(Application.StartupPath, 1) = "\" Then
sConnstring = New SqlConnection("server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678")
Else
sConnstring = New SqlConnection("server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678")
End If
Return sConnstring
End Function
The parameter you have hardcoded inside New SqlConnection is the actual Connection String.
You may want to write something like:
sConnstring = "server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678"
myConnection = New SqlConnection(sConnstring)
So your function Get_Constring should just return the string, not an entire connection.
Function Get_Constring()
If Microsoft.VisualBasic.Right(Application.StartupPath, 1) = "\" Then
sConnstring = "server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678"
Else
sConnstring = "server=192.168.1.111\SQLSERVER;database=Common_DB;User ID=sa;Password=12345678"
End If
Return sConnstring
This should work as intended.
Conversion from type 'SqlConnection' to type 'String' is not valid.
This error message is very clear. You cannot convert a (new) SqlConnection to a string (sConnstring).

Condition or Rule when Importing Excel data to SQL

At line 4 of my code, how or is it possible to have a condition in there?
For example:
Dim expr As String = "SELECT * FROM [Sheet1$] WHERE excelColumn1 <> NULL"
I have tried it, but it gives an Error: No value given for one or more required parameters.
Dim ExcelConnection As New System.Data.OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\z.fontanilla\Documents\etl2.xlsx;Extended Properties=""Excel 12.0 Xml;HDR=Yes""")
ExcelConnection.Open()
Dim expr As String = "SELECT * FROM [Sheet1$]"
Dim objCmdSelect As OleDbCommand = New OleDbCommand(expr, ExcelConnection)
Dim objDR As OleDbDataReader
Dim SQLconn As New SqlConnection()
Dim ConnString As String = "Data Source=cyayay\sqlexpress;Initial Catalog=reportingDB;Integrated Security=True"
SQLconn.ConnectionString = ConnString
SQLconn.Open()
Using bulkCopy As SqlBulkCopy = New SqlBulkCopy(SQLconn)
bulkCopy.DestinationTableName = "tFalse"
Try
objDR = objCmdSelect.ExecuteReader
bulkCopy.BatchSize = 5000
bulkCopy.WriteToServer(objDR)
objDR.Close()
SQLconn.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End Using
ExcelConnection.Close()