vb.net how to display Selected data from postgresql? - vb.net

why is it even though i declared correctly the database name and its table, the error always saying TracingApp_fmemployeesuppliersfeedbackquestions is not exists, I just want that if the firstname and lastname exist in the database the record of that i search will show in the DataGridView1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim dt As New DataTable
Dim firstname = firstnametextbox.Text.Trim()
Dim lastname = lastnametextbox.Text.Trim()
Try
Using MyCon As New Odbc.OdbcConnection("Driver={PostgreSQL ANSI};database=contacttracing;server=localhost;port=5432;uid=*****;sslmode=disable;readonly=0;protocol=7.4;User ID=*****;password=*****;"),
cmd As New Odbc.OdbcCommand("SELECT firstname= '" & firstname & "', lastname= '" & lastname & "' FROM TracingApp_fmemployeesuppliersfeedbackquestions ", MyCon)
MyCon.Open()
dt.Load(cmd.ExecuteReader)
End Using
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
DataGridView1.DataSource = dt
End Sub
Here is my postgresql tree
this is the error i get
UPDATE
ive tried this also
Odbc.OdbcCommand("SELECT firstname= '" & firstname & "', lastname= '" & lastname & "' FROM public.TracingApp_fmemployeesuppliersfeedbackquestions ", MyCon)
it didnt work also...

I suggest to surround the table name in quotes:
"SELECT * FROM ""TracingApp_fmemployeesuppliersfeedbackquestions"" "
"" being what one uses to get a single " into a VB string
I suggest this because I'm aware that PG converts all non quoted table names to lowercase (as can be seen in your "relation does not exist" error message) but the query tool tree shows that some letters in the table names are upper case, so I suspect the table names were created as case sensitive, and TracingApp_fmemployeesuppliersfeedbackquestions is different to tracingapp_fmemployeesuppliersfeedbackquestions
It might be less annoying for you to change your table names, if no other app is using the database, so you don't have to fill your VB strings up with lots of ""

Related

How to split a joined column into its seperate columns and use the data? (VB.Net + SQL Management Studio)

This is gonna be somewhat tricky to explain but I'll try to break it down. Note that this is created using VB.Net 2003.
I have a Web page which requires user to input data to save into SQL. They are required to fill in:
Course: {Select via drop-down table} \\ Variable name = Crse
Emp No: {Manually type the number} \\ Variable name = Emp
For the drop down list for Course, the data is obtained from an SQL table 'Course', with the columns:
| Course Code | Course Title |
Once input complete, I can then save the entry into my Emp_Course table in SQL using the query:
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"Crse.SelectedItem.ToString & "')"
Previously the drop-down list only needed the show Course Code, but now I'm required to add in the Course Title as well. Another thing to point out is that the Course Code has no fixed length.
Drop-down list sample:
Before:
A001
BX003
After:
A001 - Course A
BX003 - Course BX
Meaning I have to change the logic in populating the drop-down list:
Dim list As New SqlCommand("select CourseCode + ' - ' " _
& "+ CourseTitle as Course from [SQL].[dbo].[Course] " _
& "order by CourseCode", SQLDB)
Now comes my main issue, when I want to save my entry, the program obviously gives an error because the SQL still refers to the Course Code only, while my drop-down list is a Code + Description hybrid.
So since now I've made my course selection, how am I supposed to add to my SQL to update Emp_Course table to tell it to select the Course Code part of my hybrid selection?
I would just go to the Course table and just add a new Code + Title column and refer to that, but I have no authority to modify it and need to work around it.
Any other alternatives I can use?
Dim arr As String() = Crse.SelectedItem.ToString().Split(New Char() {"-"c})
Dim courseCode AS String = Trim(arr(0))
Dim updateState As String = "insert into EMP_COURSE" _
& "(Employee_No, CourseCode)" _
& "values('" & Emp.Text & "', " _
& "'"courseCode & "')"
Comments and explanations in line.
Imports System.Data.SqlClient
Public Class WebForm1
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not IsPostBack Then
Crse.DataSource = CreateDataSource()
'Course is the concatenated string returned from
'the database containing the CourseCode and the CourseTitle
Crse.DataTextField = "Course"
Crse.DataValueField = "CourseCode"
Crse.DataBind()
Crse.SelectedIndex = 0
End If
End Sub
Protected Function CreateDataSource() As DataTable
Dim dt As New DataTable
Using SQLDB As New SqlConnection("Your connection string")
'This selects the CourseCode as a separate column and the string called Course
'containing the CourseCode and the CourseTitle
Using cmd As New SqlCommand("select CourseCode, CourseCode + ' - ' + CourseTitle as Course from [SQL].[dbo].[Course] order by CourseCode", SQLDB)
SQLDB.Open()
dt.Load(cmd.ExecuteReader)
End Using
End Using
Return dt
End Function
Protected Sub UpdateDatabase()
Using SQLDB As New SqlConnection("Your connection string")
Using cmd As New SqlCommand("insert into EMP_COURSE (Employee_No, CourseCode) values(#EmpNo, #CourseCode);", SQLDB)
'I guessed at the SqlDbType. Check the database for the real data types.
cmd.Parameters.Add("EmpNo", SqlDbType.Int).Value = CInt(Emp.Text)
'Always use parameters to prevent SQL injection
'The SelectedValue will return the CourseCode
cmd.Parameters.Add("#CourseCode", SqlDbType.VarChar).Value = Crse.SelectedValue
SQLDB.Open()
cmd.ExecuteNonQuery()
End Using
End Using
End Sub
Protected Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
UpdateDatabase()
End Sub
End Class
Split the value and get the course code as in the following code. Hope it helps.
Dim Str = Crse.SelectedItem.ToString
Dim strArr() As String
strArr = Str.Split(CType("-", Char()))
Dim CourseCode As String = strArr(0).Trim

Er : Syntax error in INSERT INTO statement Visual Basic 2017 using MC Access 2016 , oleDb 4.0

I am trying to insert data in my access database but i am getting a Syntax error in INSERT statemnt exception.Can someone please help me troubleshoot this error...Maybe my inset statement is not correct ?
Private Sub btnSave_Click(sender As Object, e As EventArgs) Handles btnSave.Click
Try
If cmbTo.Text = "" Or cmbfrom.Text = "" Or cmbDay.Text = "" Or cmbMonth.Text = "" Or cmbYear.Text = "" Or cmbListBus.Text = "" Then
MsgBox("Please Insert Your Destination")
Else
Dim conn As New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Hacke\source\repos\Student\Database\studentdatabase.mdb")
Dim insert As String = "INSERT INTO [BUSTICKET] VALUE ('" & cmbfrom.Text & "','" & cmbTo.Text & "','" & cmbDay.Text & "','" & cmbMonth.Text & "','" & cmbYear.Text & "','" & cmbListBus.Text & "');"
Dim cmd As New OleDbCommand(insert, conn)
conn.Open()
cmd.ExecuteNonQuery()
MsgBox("Success")
conn.Close()
End If
Catch ex As Exception
MsgBox("Err : " & Err.Description)
End Try
End Sub
End Class
A few mistakes in your post has made it a bit difficult for us to understand.Anyway,i've submitted an edit of your post.
The problem i see so far is that you haven't defined which table you want to insert the data in.For example,if your table name is Students ,then a sample sql/OleDb statement might look like
"Seletct * from Students",ConnectionString
Note : In the following statement,i used (*) which means i am not selecting/targeting any particular column/cell but all the columns/cells.This statement is used for various purposes specially when retrieving data from the database.
However,your motive is to insert data in the database.
The INSERT statement for any database software(AFAIK) must include the Table name you are targeting,the Column/Cell headers/names.Let's assume your Table name is Students and you want to insert data in FirstName,LastNmae columns.Then a sample Insert statement may look like :
"Insert into Students(FirstName,LastName)values(#fname,#lname)", ConnectionString
Now,NOTE THAT i am not adding the values directly in the statement.you can do that if you want.However,in this sample insert statement,i am rather defining some parameter names like#Fname and #Lname.This will be used later on to finally insert data into the table's columns.
Now,if you go with my sample code,you must assign some values to these parameters from your application.We have 2 parameters now and they are #Fname and #Lname.We now need to add literal values to them.Let's assume the values are coming from TextBoxes.
MyOledbCommand.Add("#Fname",OledbDatatype.VarChar).Value = FNameTxtBox.Text
'Or you can use :
MyOledbCommand.AddWithValue("#Fname",FNameTxtBox.Text)
After you are done assigning the textboxes(or some string or whatever) as the values,it is time to execute the command so that the data inserts.For that,we generally call :
MyOleDbCommand.ExecuteNonQuery()
So,here's a full sample :
Dim con as New oleDbConnection = "ConnectionStringHere"
Con.open
Dim MyOleDbCommand as new OleDbCommand("Insert into Students(FirstName,LastName)values(#fname,#lname)", con)
MyOledbCommand.AddWithValue("#Fname",FNameTxtBox.Text)
MyOledbCommand.AddWithValue("#Lname",LNameTxtBox.Text)
MyOleDbCommand.ExecuteNonQuery
Con.Close
Hope this helps :)

How do I update a specific row in access using SQL update? In my current code I keep getting the error data type mismatch

In my current code, I keep getting the error data type mismatch most of it worked before I added the SQL where statement to select a specific id
Private Sub UpdateButton_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles UpdateButton.Click
'tells your program the data source
provider = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=" 'refrences to the provider
datafile = "C:\Users\Abdulaleem\Documents\Books.accdb" 'refers to the location of the file
connectstring = provider & datafile ' combines the 2 variables
myconnect.ConnectionString = connectstring ' this class allows you to connect to the database
myconnect.Open() ' opens the databse
Dim sqlupdate As String
sqlupdate = "Update BooksTbl set BookName='" & TitleTEXT.Text & "' , [BookAuthor]='" & AuthorTEXT.Text & "',[Genre] ='" & GenreTEXT.Text & "',[IsAvailable] = " & status & ",[DatePublished] = '" & DateTimeCHANGER.Text & "' , [PictureLocation] = '" & PiclocTEXT.Text & "' WHERE [ID] = '" & idshower.Text & "'"
Dim cmd As OleDbCommand = New OleDbCommand(sqlupdate, myconnect) 'creating new database object
Try
cmd.ExecuteNonQuery() ' executes our sql query
cmd.Dispose() 'deleting from ram to stop interferences
myconnect.Close() 'closes database and connection
TitleTEXT.Clear()
AuthorTEXT.Clear()
GenreTEXT.Clear()
Catch ex As Exception ' if the programs crashes then it will be caught here and put into the ex variable
MsgBox(ex.Message) ' shows what error occured
myconnect.Close()
End Try
myconnect.Close()
Assuming that your [ID] column is an integer, try changing it from:
...WHERE [ID] = '" & idshower.Text & "'"
to
...WHERE [ID] = " & idshower.Text
In access, attempting to compare a number with a string results in the message "Data type mismatch in criteria expression".
Note: Unless you are certain the idshower.text actually contains a number, it'd be good practice to check this before executing the query, or access will think you're trying to use a parameter.
Also: You might want to look into parameterised queries which, although they usually result in more lines of code, protect you against things like SQL injection attacks and can perform some basic type conversion for you.

How to get the ID of the most recently inserted Access record? [duplicate]

I have the following set of code for a Sub program. It's inserting a row into a MSAccess Database using data provided in the containing form. What I would like to do is grab the ID number of this added record so that it can be set for a property of a window that is invoked when successfully added. I tried looking this up but I get something about ##IDENTITY but it's using an entirely different way of connecting.
Private Sub CreateTournament_Click(sender As System.Object, e As System.EventArgs) Handles CreateTournament.Click
' TODO: Check the form for errors, or blank values.
' Create the tournament in the database, add the values where needed. Close the form when done.
Dim cn As OleDbConnection
Dim cmd As OleDbCommand
Dim dr As OleDbDataReader
Dim icount As Integer
Dim str As String
Try
cn = New OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source='C:\Master.mdb'")
cn.Open()
str = "insert into Tournaments (SanctioningID,TournamentName,TournamentVenue,TournamentDateTime,TournamentFirstTable,Game,Format,OrganizerID) values(" _
& CInt(SanctioningIDTxt.Text) & ",'" & Trim(TournamentNameTxt.Text) & "','" & _
"1" & "','" & EventDateTimePck.Value & "','" & TableFirstNumberNo.Value & "','" & GameList.SelectedIndex & "','" & FormatList.SelectedIndex & "','" & Convert.ToInt32(ToIDTxt.Text) & "')"
'string stores the command and CInt is used to convert number to string
cmd = New OleDbCommand(Str, cn)
icount = cmd.ExecuteNonQuery
MessageBox.Show(icount)
'displays number of records inserted
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
Me.Close()
Dim n As New TournamentWindow ' Open a new Tournament window if everything is successful
n.TournID = Counter '<< This should be set to the ID of the most recently inserted row
n.Show(HomeForm)'Invoke the form and assign "HomeForm" as it's parent.
End Sub
Assuming you have an auto increment column in the Tournaments table, you can do a "SELECT ##IDENTITY" to get the id of the last inserted record.
BTW, is the SanctioningIDTxt.Text unique? If so, can't you use that?

datatypes dont match, correct query and table

Got a new one for you, tried everything i could think of but without succes.
I want to be able to edit some textboxes and then update their records in the database. I use this code:
Private Sub btnUpdate_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnUpdate.Click
connection.Open()
cmdupdate.CommandText = "UPDATE tbl_stal SET Locatie = '" & cbLocatienummer.Text & "', Coordinaten = '" & txtCoordinaten.Text & "' WHERE ID = '" & cbID.Text & "'"
cmdupdate.CommandType = CommandType.Text
cmdupdate.Connection = connection
cmdupdate.ExecuteNonQuery()
MsgBox("De gegevens zijn aangepast." & vbNewLine & "The data has been modified." & vbNewLine & "Die Daten sind angepasst.", MsgBoxStyle.OkOnly, "Voersoorten")
connection.Close()
cmdupdate.Dispose()
I am certain that the names of the database table and it's fields are correct, tried using both numerical and textbased settings on the table fields(as normally they should be numerical, but they might be text too. )
However, when i load some data from the datagridvieuw into the textboxes, change the coordinates(for example) and hit the updatebutton, it will give me the error that the datatypes don't match.
Apart from the above, what else can it be?
When you write data to a database table using any kind of sql text you should NEVER use string concatenation to build the SQL. This because you could have problems in the string supplied (what if one of these strings contains an embedded single quote?) and because taking the user input and attaching it to your command is a really dangerous practice that leads to Sql Injection
(Well MS-Access doesn't support multiple commands so you are a bit safer here)
So you should rewrite your query in this way
Dim cmdText = "UPDATE tbl_stal SET Locatie = ?, Coordinaten = ? WHERE ID = ?"
Using connection = new OleDbConnection(.....)
Using cmdUpdate = new OleDbCommand(cmdText, connection)
connection.Open()
cmdUpdate.Parameters.AddWithValue("#p1", cbLocatienummer.Text)
cmdUpdate.Parameters.AddWithValue("#p2", txtCoordinaten.Text)
cmdUpdate.Parameters.AddWithValue("#p3", Convert.ToInt32(cbID.Text))
cmdUpdate.ExecuteNonQuery()
End Using
End Using
Notice that you should provide a parameter with the exact datatype that matches the datatype of your field, strings for text fields, numbers for numeric fields.