I am trying to allow the user to select which table they want to take their data from, the UserID text box(UserIDtb) is where the user inputs the table they want. I've tried several different ways of doing it but cant seem to allow the user to select a specific table. This is the code I have so far:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles ConfirmIDButt.Click
Chart1.Series.Add("Score")
Dim Conn As OleDbConnection = New OleDbConnection
Dim provider = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source ="
Dim dataFile = "\users.accdb" ' Change it to your Access Database location
Conn.ConnectionString = provider & dataFile
Conn.Open()
Dim cmd As OleDbCommand = New OleDbCommand("SELECT [Month], [Score] FROM [Table]", Conn)
Dim dr As OleDbDataReader = cmd.ExecuteReader
While dr.Read
Chart1.Series("Score").Points.AddXY(dr("Month").ToString, dr("Score").ToString)
End While
dr.Close()
cmd.Dispose()
End Sub
Related
first time poster here.. I've been struggeling with this problem for a while.
This piece of code checks if the combination of username and password exist, and if it does it redirects to a new form.
The problem is that i also wanna check if a bit value is true or false, and if it then redirect to another page aswell. I just dont know how to.
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles
Button1.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim myData As SqlClient.SqlDataReader
Dim Dataset As New DataSet
Dim adaptor As New SqlClient.SqlDataAdapter
connection.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\NewFolder1\Members.mdf;Integrated Security=True")
command.CommandText = "SELECT * FROM [User] WHERE username = '" & TextBox1.Text & "' AND password= '" & TextBox2.Text & "';"
connection.Open()
command.Connection = connection
adaptor.SelectCommand = command
adaptor.Fill(Dataset, 0)
myData = command.ExecuteReader
If Not myData.HasRows Then
TextBox1.Clear()
TextBox2.Clear()
MsgBox("Forkert login, prøv igen")
ElseIf myData.HasRows Then
Me.Hide()
LoggetInd.Show()
End If
Here is what you can do:
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
Dim connection As New SqlClient.SqlConnection
Dim command As New SqlClient.SqlCommand
Dim myData As SqlClient.SqlDataReader
connection.ConnectionString = ("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\NewFolder1\Members.mdf;Integrated Security=True")
'Don't use SELECT *, call out the columns you want by name, in the order you want them
command.CommandText = "SELECT Username, Password, Bit1 FROM [User] WHERE username = '" & TextBox1.Text & "' AND password= '" & TextBox2.Text & "';"
connection.Open()
command.Connection = connection
myData = command.ExecuteReader(CommandBehavior.CloseConnection)
Dim dbUsername As String, dbPassword As String, dbBit1 As Boolean
If myData.Read Then
'Access the data in the datareader using a 0-based index
'Be careful as this requires you to know the datatype in the database
'If you have a 64bit integer stored in the database,
'you can't call GetInt32, you have to call GetInt64.
dbUsername = myData.GetString(0)
dbPassword = myData.GetString(1)
dbBit1 = myData.GetBoolean(2)
End If
'Don't forget to Close all your DataReaders
myData.Close()
If dbUsername = "" Then
TextBox1.Clear()
TextBox2.Clear()
MsgBox("Forkert login, prøv igen")
Else
If dbBit1 Then
'Redirect as needed
Else
Me.Hide()
LoggetInd.Show()
End If
End If
End Sub
Plutonix is right, you need to use a hash to encrypt/store your passwords. You also need to use SQL parameters. Your current method is an SQL injection playground, among other things.
Call Close on all your datareaders when you are done with them, if not you will have open SQL connections all over the place. When you call ExecuteReader, be sure to use CommandBehavior.CloseConnection. This closes the Connection automatically after you Close the datareader.
This will hopefully get your code working, but you do need to make additional changes for security and stability.
-E
I am making a railway reservation system in which I want the user to see his booking history. In the reservation system there is multiple login facility . Many users can create account and book tickets . So, a user can check his bookings which were made from his account . Due to this reason , I thought that I should compare the username of the currently opened account with the account username column present in the database . If the username of the currently opened account matches with the account username in the database , then it will fetch all those records under that name but when I try to execute, it gives me an error.
Imports System.Data.OleDb
Public Class Form12
Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0; Data Source=C:\Users\AMEN\Documents\Railway.accdb"
Dim MyConn As OleDbConnection
Dim da As OleDbDataAdapter
Dim ds As DataSet
Dim tables As DataTableCollection
Dim source1 As New BindingSource
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
MyConn = New OleDbConnection
MyConn.ConnectionString = connString
ds = New DataSet
tables = ds.Tables
da = New OleDbDataAdapter("Select [T.Tnumber], [T.P_Name], [T.Age],[T.Train_Name], [T.Seat_No], [T.Berth],[t.R_Name], [t.Starting_Point],[t.Destination], [t.Departure], [t.Arrival], [t.Fare] from Table2 ,Table1 where T.PNR_Number=t.PNR_Number and T.Account_User=My.Settings.Username", MyConn)
da.Fill(ds, "Table2")
Dim view As New DataView(tables(0))
source1.DataSource = view
DataGridView1.DataSource = view
End Sub
End Class
I think something is wrong with da.Fill(ds, "Table2") but I don't know how to correct it.
In your SELECT statement you are comparing against My.Settings.Username, and I am imagining that this string doesn't exist in your db. You want the value inside the My.Settings.Username, we can just use string concatenation to add that to the end (as long it is a string!).
da = New OleDbDataAdapter("Select [T.Tnumber], [T.P_Name], [T.Age],[T.Train_Name], [T.Seat_No], [T.Berth],[t.R_Name], [t.Starting_Point],[t.Destination], [t.Departure], [t.Arrival], [t.Fare] from Table2 ,Table1 where T.PNR_Number=t.PNR_Number and T.Account_User=" + My.Settings.Username, MyConn)
Hello I'm having problem saving record in my database ,When I debug the program it says "OLEDB Execption was unhandled, Syntax Error in update statement"
Can you Help me?
Is this The right Code?
Imports System.Data.OleDb
Public Class Form2
Dim contr As String = "Provider= Microsoft.Jet.OLEDB.4.0; Data Source= C:\Users\Administrator\Desktop\Users.mdb;"
Private Sub Form2_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
Dim con As New OleDbConnection(contr)
con.Open()
Dim cmd As New OleDbCommand("UPDATE Usertable SET Username = #Username, Password = #Password WHERE id = #id", con)
cmd.Parameters.AddWithValue("#Username", TextBox1.Text)
cmd.Parameters.AddWithValue("#Password", TextBox2.Text)
cmd.Parameters.AddWithValue("#Id", Label3.Text)
cmd.ExecuteNonQuery()
con.Close()
End Sub
End Class
Password is a reserved keyword for MS-Access. Use it enclosed in square brakets
Dim cmd As New OleDbCommand("UPDATE Usertable SET Username = #Username, " & _
"[Password] = #Password WHERE id = #id", con)
Access/OLE doesn't like named parameters. You need to use ? placeholders:
UPDATE Usertable SET Username = ?, Password = ? WHERE id = ?
Then to match each parameter value with the placeholder, you must add them to the Parameters collection in the order the placeholder is used in the query, rather than by name.
I am writing a simple SQL Server query operation through vb.net application. I am having some strange problems.
This line is giving error:
dr = cmd.ExecuteReader()
This is giving me error "Invalid column name abhishek." Here abhishek is the data I am providing in TextBox1.Text. I am not able to think of any mistake by my side as this is a simple query. I am able to run other queries, like delete queries, on same table in a different form, so its not a database problem.
Any clue what's going wrong?
reginfo is the table name. name is one of the fields.
My complete code is below:
Imports System.Data.Sql
Imports System.Data.SqlClient
Public Class Form9
Dim con As New SqlConnection()
Dim cmd As New SqlCommand()
Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
cmd.CommandText = "select * from reginfo where name=" + (TextBox1.Text) + ""
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader() '<<< This line is creating problem
If dr.Read() Then
TextBox2.Text = dr(0).ToString()
End If
con.Close()
End Sub
Private Sub Form8_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
con.ConnectionString = "Data Source=ABHISHEK-PC\SQLEXPRESS;Initial Catalog=locserver;Integrated Security=True;Pooling=False"
End Sub
Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
End Sub
End Class
if the name field is a text field then you need to enclose your textbox in single quotes, but this is bad advice to give. The only good approach to this kind of situations is through a parameterized query
cmd.CommandText = "select * from reginfo where name=#name"
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Dim dr As SqlDataReader
con.Open()
cmd.Connection = con
dr = cmd.ExecuteReader()
Also, do not keep global objects like a connection or a command. It is always a good practice to instantiate a connection as late as possible and close it as soon as possible, better inside a Using block
Using con = New SqlConnection(...connection string here....)
Using cmd = New SqlCommand("select * from reginfo where name=#name", con)
con.Open()
cmd.Parameters.AddWithValue("#name", TextBox1.Text)
Using dr = cmd.ExecuteReader
'.... do you reading
End Using
End Using
End Using
In this way the connection is kept open for the minimum time possible and, also in case of exceptions is closed and disposed appropriately.
I use Visual Basic 2010 and Microsoft SQL Server 2008. I have my database and my table and i made the connection (at least i think i did) in VB using only the interface.
What i want to know is how to get data from the database and use it into my VB project. I have of course searched for solutions already but the differences i find only confuse me more. What i need to know are the basics, the tools/objects and procedures to retrieve the data.
What i try to do at the moment is make a simple selection and put that data into a listbox right when the program starts, like this:
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
SqlConnection1.Open()
SqlConnection1.Close()
End Sub
End Class
1) Create your connection string
Dim connectionString As String = "Data Source=localhost;........."
2) Connect to your Database
Dim connection As New SqlConnection(connectionString)
conn.Open()
3) Create a Command and the query
Dim command As New SqlCommand("SELECT * FROM Product", connection)
Dim reader As SqlDataReader = command.ExecuteReader() //Execute the Query
4) Retrieve your result. There are several ways
Dim dt As New DataTable()
dt.Load(reader)
'Close the connection
connection.Close()
5) Bind to your list box
myListBox.ItemSource = dt
Full code here
Using connection As New SqlConnection(connectionString)
Dim command As New SqlCommand("Select * from Products", connection)
command.Connection.Open()
SqlDataReader reader = command.ExecuteReader()
End Using
For more info
SQLCommand
SqlConnection1.Open()
using table As DataTable = New DataTable
using command as SqlCommand = New SqlCommand("SELECT blah blah", SqlConnection1)
using adapter As SqlDataAdapter = new SqlDataAdapter(command)
adapter.Fill(table)
end using
end using
for each row As DataRow in table.Rows
' add each listbox item
listbox1.Items.Add(row("column name"))
next
end using
SqlConnection1.Close()