vb.net windows form select query using postgresql server - vb.net

I am new in vb.net, how do i conduct select query in my windows forms using postgresql server?
this is my connection, (actually i dont know if this is working but i didnt receive any error and the message box appear if i button is clicked)
here is code so far
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim MyCon As New Odbc.OdbcConnection
MyCon.ConnectionString = "Driver={PostgreSQL ANSI};database=*****;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=******;password=*****;"
MyCon.Open()
If MyCon.State = ConnectionState.Open Then
MsgBox("Connected To PostGres", MsgBoxStyle.MsgBoxSetForeground)
End If
End Sub

In .Net we have Using...End Using blocks that will close and dispose objects that use unmanaged code. Connections fall into this type of object; any object class that has a .Dispose method.
You can pass your connection string directly to the constructor of the connection.
We also have Try...Catch...Finally....End Try for exception handling.
To test your connection:
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=*****;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=******;password=*****;")
MyCon.Open()
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
For help with the connection string itself check https://www.connectionstrings.com/postgresql/
There are several ways to query your database in ADO.net. Study up on ADO.net. The following is one way.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=*****;server=localhost;port=5432;uid=postgres;sslmode=disable;readonly=0;protocol=7.4;User ID=******;password=*****;"),
cmd As New Odbc.OdbcCommand("Select * From SomeTable;", MyCon)
MyCon.Open()
dt.Load(cmd.ExecuteReader)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
DataGridView1.DataSource = dt
End Sub

Related

How do I resolve SQL ConnectionString error?

I have a Form with a DataGridView and a Button. They are interacting with an Access (.mdb) database. When the Button is clicked, I want it to update the data in the Table.
I get the following error:
Value of type 'OleDbConnection' cannot be converted to
'SqlConnection'.
My code:
Imports System.Data.OleDb
Imports System.Data.SqlClient
Public Class Form1
Public conn As New OleDbConnection
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim DS As New DataSet
Dim DT As New DataTable
DS.Tables.Add(DT)
Dim objConn As String = "Provider=Microsoft.JET.OLEDB.4.0; Data Source = Swiftest.mdb"
conn.ConnectionString = objConn
Dim objDA As New OleDb.OleDbDataAdapter("SELECT * FROM tblOptions", conn)
objDA.Fill(DT)
DataGridView1.DataSource = DT.DefaultView
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim SqlQuery As String = "'UPDATE tblOptions Set fldShow = '1' WHERE fldID = '13'"
conn.Open()
Dim com As New SqlCommand(SqlQuery, conn)
End Sub
End Class
Thanks for reading
Several of the database objects available is ADO.net have .Dispose methods. If an object has a dispose method it may be using unmanaged resources (resources outside the .net framework). These objects need to release these resources and they do this in there dispose methods. Fortunately the .net languages provide Using...End Using blocks which will guarentee that .Dispose is called even if there is an error.
In view of this create your database objects in the Sub or Function where they are used so they can be enclosed in Using blocks. Note the comma at the end of the connection Using line. This indicates that the object on the next line (the command) is included in the same Using block.
In your Form.Load event, you never used the adapter or the dataset. Just load the datatable.
Open the connection at the last possible moment, directly before the .Execute... and close immediately with the End Using. In your Button1.Click event you open a connection, never execute anything and never close it.
In your update command you provide literals as String. Normally, an ID field is an Integer. Check you database for the datatype of the fields. If you want to provide values that are not literals use parameters.
Private connStr As String = "Provider=Microsoft.JET.OLEDB.4.0; Data Source = Swiftest.mdb"
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Dim DT As New DataTable
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand("SELECT * FROM tblOptions", conn)
conn.Open()
Using reader = cmd.ExecuteReader
DT.Load(reader)
End Using
End Using
DataGridView1.DataSource = DT.DefaultView
End Sub
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Using conn As New OleDbConnection(connStr),
cmd As New OleDbCommand("UPDATE tblOptions Set fldShow = '1' WHERE fldID = '13'", conn)
conn.Open()
cmd.ExecuteNonQuery()
End Using
End Sub

Delete selected row from DataGridView and MS-Access Database

I am trying to delete the selected row from DataGridView and MS-Access database..
Private Sub ButtonEditDelete_Click(sender As Object, e As EventArgs) Handles ButtonEditDelete.Click
If Not Connection.State = ConnectionState.Open Then
Connection.Close()
End If
Try
If Me.DataGridViewEdit.Rows.Count > 0 Then
If Me.DataGridViewEdit.SelectedRows.Count > 0 Then
Dim intStdID As Integer = Me.DataGridViewEdit.SelectedRows(0).Cells("Username").Value
Connection.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Johnster\documents\visual studio 2015\Projects\Cash register\Cash register\Database11.accdb;Jet OLEDB:Database Password="
Connection.Open()
Command.Connection = Connection
Command.CommandText = "DELETE From MasterUser WHERE ID=? And Username=? And UserFullname=? AND Password=?"
Dim res As DialogResult
res = MsgBox("Are you sure you want to DELETE the selected Row?", MessageBoxButtons.YesNo)
If res = DialogResult.Yes Then
Command.ExecuteNonQuery()
Else : Exit Sub
End If
Connection.Close()
End If
End If
Catch ex As Exception
End Try
End Sub
Replace your (Try) Part with this code:
Using cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\Johnster\documents\visual studio 2015\Projects\Cash register\Cash register\Database11.accdb;Jet OLEDB:Database Password=")
cn.Open()
Try
For Each row As DataGridViewRow In DataGridViewEdit.SelectedRows
Using cm As New OleDbCommand
cm.Connection = cn
cm.CommandText = "DELETE * FROM CheckDJ WHERE [Username]= #myuser"
cm.CommandType = CommandType.Text
cm.Parameters.AddWithValue("#myuser", CType(row.DataBoundItem, DataRowView).Row("Username"))
cm.ExecuteNonQuery()
End Using
Next
Catch ex As Exception
MsgBox(ex.Message)
End Try
cn.Close()
End Using
then clear your datasource of datagridview by this line:
DataGridViewEdit.Datasource = nothing
then repeat the code part that is responsible of filling the datagridview from the database
You are going about this in very much the wrong way. The proper way to do it would be to use an OleDbDataAdapter to populate a DataTable, bind that to a BindingSource and bind that to your DataDridView. You can then call RemoveCurrent on the BindingSource to set the RowState of the DataRow bound to the selected DataGridViewRow to Deleted. You then use the same OleDbDataAdapter to save the changes from the DataTable back to the database. The Fill method of the data adapter retrieves data and the Update method saves changes. You can call Update every time there's a change to save or you can let the user make all there changes locally first and then save them all in a single batch. Here's a code example:
Private connection As New OleDbConnection("connection string here")
Private adapter As New OleDbDataAdapter("SELECT ID, Name, Quantity, Unit FROM StockItem",
connection)
Private builder As New OleDbCommandBuilder(adapter)
Private table As New DataTable
Private Sub InitialiseDataAdapter()
adapter.MissingSchemaAction = MissingSchemaAction.AddWithKey
End Sub
Private Sub GetData()
'Retrieve the data.
adapter.Fill(table)
'Bind the data to the UI.
BindingSource1.DataSource = table
DataGridView1.DataSource = BindingSource1
End Sub
Private Sub SaveData()
'Save the changes.
adapter.Update(table)
End Sub
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
InitialiseDataAdapter()
GetData()
End Sub
Private Sub deleteButton_Click(sender As Object, e As EventArgs) Handles deleteButton.Click
BindingSource1.RemoveCurrent()
End Sub
Private Sub saveButton_Click(sender As Object, e As EventArgs) Handles saveButton.Click
SaveData()
End Sub
In certain circumstances, you may not be able to use an OleDbCommandBuilder and would have to create the InsertCommand, UpdateCommand and DeleteCommand yourself.

VB.Net not able to connect to SQL

Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Server=localhost;Initial Catalog=acernis;User ID=root;Password=password"
cnn = New SqlConnection(connetionString)
Try
cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
Currently in my code I have the code above the SQL username and pass are correct as is the DB. I have WAMP running and am using Navicat to make sure I can connect. What is wrong?
if you are using MS SQL server then your issue is with the connection string. try this one :
connetionString = "Server=localhost;Database=acernis;User ID=root;Password=password"
however if you mean MySQL then you need to change more than just the connectio string
try this:
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim connetionString As String
connetionString = "Server=localhost;Database=acernis;Uid=root;Pwd=password;"
Dim conn As New MySqlConnection(connetionString)
Try
conn.Open()
MsgBox("Connection Open ! ")
Catch ex As MySqlException
MsgBox("Can not open connection Error: " & ex.ToString())
Finally
conn.Close()
End Try
End Sub
to find out what is the connection string that best suites you refer to the website
http://www.connectionstrings.com/
Private Sub Button5_Click_1(sender As Object, e As EventArgs) Handles Button5.Click
Dim connetionString As String
Dim cnn As SqlConnection
connetionString = "Server=localhost\<InstanceName>;Initial Catalog=acernis;User ID=root;Password=password"
cnn = New SqlConnection(connetionString)
Try
if not cnn.State=ConnectionState.Open then cnn.Open()
MsgBox("Connection Open ! ")
cnn.Close()
Catch ex As Exception
MsgBox("Can not open connection ! ")
End Try
End Sub
As per observation, if you are using SQL Server, you need to specify the <Instance Name> in Server property.
Plus, do not use class Exception in catch section, Instead, use specific exceptoin class; in this case, use SQLException

How to update SQLite database from DataGridView in Visual Basic 2013 .net?

I am displaying data from SQLite table into a DataGridView as following -
Private Sub Subjects_Manager_Load(sender As Object, e As EventArgs) Handles MyBase.Load
con = New SQLiteConnection("Data Source = c:\demo\test.db;Version=3;")
con.Open()
sql = "SELECT * FROM med_subjects"
da = New SQLiteDataAdapter(sql, con)
da.Fill(ds, "SubjectsList")
DataGridView1.DataSource = ds.Tables("SubjectsList").DefaultView
With DataGridView1
.RowHeadersVisible = False
.Columns(0).HeaderCell.Value = "Subject Id"
.Columns(1).HeaderCell.Value = "Subject Name"
End With
DataGridView1.Sort(DataGridView1.Columns(0), System.ComponentModel.ListSortDirection.Ascending)
con.close()
End Sub
I want to save changes done in DataGridView (either Updation of Row/s or Insertion of Row/s) back to SQLite table. But I couldn't find a way to do so.
Edit 1 :
I know Insert/Update Queries of SQLite, but what I don't know is how & where to keep them so that they can be triggered in responses to changes made in DataGridView. e.g.
' I am using this variable for demonstration, in reality InsertSubjectSqlString will be equal to changes done in DataGridView
Dim InsertSubjectSqlString As String = "Insert into med_subjects (Subject_Name) Values ('_Miscellaneous')"
Dim SqliteInsertRow As SQLiteCommand
SqliteInsertRow = con.CreateCommand
SqliteInsertRow.CommandText = InsertSubjectSqlString
SqliteInsertRow.ExecuteNonQuery()
But I don't know, where should I put it?
Edit 2:
After seeing comments and answers, I came to know that there is No direct way to Insert/Update Sqlite database from DataGridView. So I was curious, if there is any event like RowSelected which would
trigger on selecting a row and get that row's data
then taking the row's data into multiple text boxes and lastly
triggering Insert/Update queries taking values from these textboxes
by a button
I know it's highly hypothetical with NO sample codes, but it's because I am asking for Event name.
Call this on LeaveRow event or CellEndEdit
Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
Dim i as integer
Try
for i = 0 to datagrid.rows.count-1
myUpdate(datagrid.item(0,i).tostring() , datagrid.item(1,i).tostring())
next
Catch ex As Exception
MsgBox(Err.Description)
End Try
End Sub
note , you can also give the column name of your grid in place of column index , like this datagrid.item("fname",i).tostring()
Here we will save in database:
Sub myUpdate(byval fname as string , byval lname as string)
Try
dim con as new sqlconnection("you connection string")
dim cmd as new sqlcommand
con.open()
cmd.connection= con
cmd.commandtext="insert into table (fname,lname) values (#fname,#lname)"
cmd.Parameters.AddWithValue("#fname", fname)
cmd.Parameters.AddWithValue("#lname", lname)
cmd.ExecuteNonQuery()
Con.close()
Catch ex As Exception
MsgBox(Err.Description)
End Try
End sub
I hope this will help you to solve !
There are many ways to manipulate data .
CristiC
I dont think you will find some magic way that the DataGridView and DataTable are going to persist things automatically to the backend SQLite database. As you are hinting at I think you will have to rely on events.
I think the event you are missing is answered here stackoverflow cell value changed event
Ok I think is better to use CellEndEdit, because LeaveRow is triggered only if you click on other row.
Look on this example.
you must use: da.Update(ds.Tables("SubjectsList").DefaultView)
Imports System.Data.SqlClient
Public Class Form1
Const connectionstring As String = "server=(local);database=TestDB;uid=sa;pwd=sa;"
Private SQL As String = "select * from customer"
Private con As New SqlConnection(connectionstring)
Private dt As New DataTable
Private adapter As New SqlDataAdapter(SQL, con)
Private commandbuilder As New SqlCommandBuilder(adapter)
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
adapter.Fill(dt)
DataGridView1.DataSource = dt
End Sub
Private Sub DataGridView1_RowLeave(ByVal sender As System.Object, ByVal e As System.Windows.Forms.DataGridViewCellEventArgs) Handles DataGridView1.RowLeave
adapter.Update(dt)
End Sub
End Class
Please use this code hopefully it will work
Imports System.Data.SQLite
Public Class Form
Dim con As New SQLite.SQLiteConnection
Dim da As New SQLite.SQLiteDataAdapter
Dim dt As New DataTable
Dim cmdbl As New SQLite.SQLiteCommandBuilder
Dim dlgResult As DialogResult
Private Sub btnUpdate_Click(sender As Object, e As EventArgs) Handles btnUpdate.Click
dlgResult = MessageBox.Show("Do you want to save the changes you made?", "Confirmation!", MessageBoxButtons.YesNo)
If dlgResult = DialogResult.Yes Then
Try
con.Open()
cmdbl = New SQLiteCommandBuilder(da)
da.Update(dt)
MsgBox("Updated successfully!")
con.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
End If
End Sub
End Class

VB2010 & MSACCESS | Object reference not set to an instance of an object

i'm making a login form and every time i try to login(whether with a correct or not user) it gives me the same error.
"Object reference not set to an instance of an object"
Here's the code:
Public Class login
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Fausto\Documents\GitHub\CRE\cre.accdb;")
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=#p_userid AND PASSWORD=#p_passw;"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
Dim da As New OleDb.OleDbDataAdapter
Private Sub login_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
'I figured how to make comments in VB! Yeey
'Temporarely redirecting to menuForm
With cmd
.Parameters.AddWithValue("p_userid", username.Text)
.Parameters.AddWithValue("p_passw", password.Text)
End With
Try
conn.Open()
Dim usr As String = cmd.ExecuteScalar.ToString
If Not (IsDBNull(usr)) AndAlso usr = username.Text Then
Me.DialogResult = Windows.Forms.DialogResult.OK
Else
Me.DialogResult = Windows.Forms.DialogResult.Cancel
End If
Catch ex As Exception
MsgBox("Could not connect to DB hahahaha" & Environment.NewLine & "Error message: " & ex.Message)
Me.DialogResult = Windows.Forms.DialogResult.Cancel
Finally
conn.Close()
Me.Close()
End Try
End Sub
Private Sub closeBtn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles closeBtn.Click
End
End Sub
Private Sub PictureBox1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles PictureBox1.Click
credits.Show()
End Sub
End Class
I'm using Visual Basic Express and Microsoft Access 2010,
Thanks :D
I saw several issues, but I think the one addressed in the question is here:
Dim conn As New OleDb.OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\Fausto\Documents\GitHub\CRE\cre.accdb;")
Dim sql As String = "SELECT USERID FROM USERS WHERE USERID=#p_userid AND PASSWORD=#p_passw;"
Dim cmd As New OleDb.OleDbCommand(sql, conn)
The problem is that those variables are class-level, initialized prior to the class constructor, and the order in which the variables are initialized is not guaranteed. What is happening is that, at the point when the New OleDb.OleDbCommand(sql, conn) code executes, the conn variable is not guaranteed to have initialized.
This omission will fly under the radar, all the way until you try to execute a command, here:
Dim usr As String = cmd.ExecuteScalar.ToString
Aside from needing parentheses for the function call, it's not unil this point that the OleDbCommand object finally tries to use the connection supplied earlier and discovers that there's Nothing there.
While I have your attention, I also need to point out that you're using the wrong parameter notation for OleDb (you need to use ? placeholders instead of #NameParameters). Also, this is a horrible way to handle authentication. NEVER store a password in plain text like that.