How do I update my database with the content of a TextBox? - sql

I have a database table with three columns: User, Pass, Money. I also have a vb form with a button and a TextBox named Money. What's the query code for updating the Money in the database, so it would be the same as the TextBox in the form?

Check Link , You are probably looking for it .
an update query can be
UPDATE Categories
SET Money = #MoneyTextBox WHERE (user = #currentUser)

With this piece of code you should be able to connect and update an Access database
Dim Connection As New OledbConnection("Provider=microsoft.Jet.oledb.4.0;DataSource=YourDatabase.mdb;")
Try
Connection.Open()
Dim Query = "UPDATE TableName SET Money = ? WHERE User = ?"
Dim command As New OleDbCommand
With command
.CommandText = Query
.Connection = Connection
.Parameters.AddWithValue("#p1", MoneyTextBox.Text)
.Parameters.AddWithValue("#p2", UserTextBox.Text)
End With
command.ExecuteNonQuery()
Catch exception As Exception
MessageBox.Show(exception.Message)
Finally
Connection.Close()
End Try

use Update Query
"update Databasename set Money='"& MoneyTextBox.Text &"' where user='" & UserTextBox.Text &"' and Pass='"PassTextBox.Text"' "

Related

VB.Net and Access - Getting Totaliser Value

I'm trying to databind a textbox to a totaliser value in an access database. I currently update the database via OleDbCommand and then edit any existing entries via databinding on the form.
I have everything working fine, but I want a textbox to show the totaliser (sum) of a particular column in the datbase. Access shows this totaliser underneath the column if the database is opened.
Is there a method to bind this value to the textbox?
Thanks
Well, however you are accessing the database, you need to make a call to get the SUM of your desired table.
If we are talking about SQL, it would look something like:
conn = New OleDbConnection(Get_Constring)
conn.Open()
cmd.Connection = conn
cmd.CommandType = CommandType.Text
sSQL = " SELECT SUM(total) AS Total From YourTable"
cmd.CommandText = sSQL
OleDbDataReader dr = cmd.ExecuteReader()
If dr.Read() Then
set total = Convert.ToInt32(dr["Total"])
End If
You could load this into a DataTable/DataSet or use the DataReader and assign the result (the sum) to a textbox, like:
TextBox1.Text = total
If you are using Linq it could look like (this is just an example):
Dim yourObject = From cust In db.Customers
Group By cust.City
Into Average(cust.Orders.Count)
Order By Average
DataGridView1.DataSource = yourObject

Visual studio Access DB insert id thats bigger as previous id

Good day reader,
i have a question about vb access insert, I have an id, but I what the next insert id to automatically get a higher number. this is the code I have so far:
Try
Dim cn As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & My.Application.Info.DirectoryPath.ToString() & "\data\testing.Accdb;Persist Security Info=False;")
If cn.State = ConnectionState.Open Then
cn.Close()
End If
cn.Open()
Dim sSQL As String = "insert into tabel1(id) values(#d1)"
Dim cmd As OleDbCommand = New OleDbCommand(sSQL, cn)
Dim id As OleDbParameter = New OleDbParameter("#d1", OleDbType.VarWChar, 25)
id.Value = 'so here I need the automatic higher number
cmd.Parameters.Add(id)
I really hope one of you guys can help me with this, thanks already.
sorry for my bad English it because I’m Dutch, if have any question I’ll try to explain it.
regards Tom
You can do this with a nested sub query:
INSERT INTO Table1 (Id,Test) SELECT TOP 1 MAX(ID) + 1,"Test Value" FROM Table1;
In this example I added another field called "Test" so you can see how you would enter values for the other fields.

Update Query in Visual Basic Express 2010

I'm trying to update an Access 2003 database using Visual Basic Express 2010 via SQL, I have so far got SELECT, DELETE and INSERT queries to work, but update will not...
con.ConnectionString = dbProvider & dbSource
con.Open() 'Open connection to the database
sqlstatement = "UPDATE users SET password = '" & NewPassword & "' WHERE USERID = " & ID & ";"
Dim dc As New OleDb.OleDbCommand(sqlstatement, con)
dc.ExecuteNonQuery()
con.Close()
Like I said, all other statements work, the error produced is:
http://i.stack.imgur.com/acFBT.png
Thank you!
The first problem is the word PASSWORD. It is a reserved keyword in MS-Access database. If you want to use it you should enclose it in square brackets.
Said that, please start using a parameterized query and not a string concatenation when you work with any type of database
So your code should be:
sqlstatement = "UPDATE users SET [password] = ? WHERE USERID = ?"
Using con = new OleDbConnection(dbProvider & dbSource)
Using dc = new OleDbCommand(sqlstatement, con)
con.Open()
dc.Parameters.AddWithValue("#p1", NewPassword)
dc.Parameters.AddWithValue("#p2", ID)
dc.ExecuteNonQuery()
End Using
End Using
You could read about the importance of Parameterized Queries and Sql Injection in many places, this link is a most famous one to start with

Error writing to SQL Database when user leaves field blank

I am creating a windows form that the user will fill out whenever we add a new employee. If I fill in the form completely, I can write to the database, but if one field gets left blank, I get an error. In the SQL table, all rows are set to allow nulls, and I can insert via SQL Server Management Studio with null values with no problems.
For brevity, I have left off a dozen or so fields, but the same error occurs if I replace this code with the code I am using.
Dim DBConnection As New SqlClient.SqlConnection
Dim cmd As New SqlClient.SqlCommand
Try
WOWConnection.ConnectionString = "Server=MyServerName;Database=Employee Database;Trusted_Connection=TRUE;"
WOWConnection.Open()
cmd.Connection = WOWConnection
cmd.CommandText = "INSERT INTO [dbo].[Employees]([FirstName],[LastName]) VALUES (#FirstName,#LastName)"
cmd.Parameters.AddWithValue("#FirstName", Me.EMP_FirstName.Text)
cmd.Parameters.AddWithValue("#LastName", Me.EMP_LastName.Text)
cmd.ExecuteNonQuery()
MsgBox("Sucess!")
Catch ex As Exception
MsgBox("error")
Finally
DBConnection.Close()
End Try
How do you handle a field being left blank on a windows form?
Test the value being inserted before passing the value to SQL.
Note that NULL value and Empty is not the same in SQL.
cmd.CommandText = "INSERT INTO [dbo].Employees VALUES
(#FirstName,#LastName)"
If Not string.IsNullOrEmpty(Me.EMP_FirstName.Text) Then
cmd.Parameters.AddWithValue("#FirstName", Me.EMP_FirstName.Text)
Else
cmd.Parameters.AddWithValue("#FirstName", DBNull.Value)
EndIf
cmd.ExecuteNonQuery()

how to get data to textbox from the database

I have a form with one combo box and text box, and an SQL database
named balance with two columns; one as customername and the other as obbalance.
I had bound all of the customer name to the combo box, now what I have to do is,
when a user selects a customer name from the combo box, the text box should show the obbalance of the selected customername; here, the customer name will not be repeated - only one name per customer.
What can I do? Please help me.
Dim conectionstring As String
conectionstring = "Data Source=.\SQLEXPRESS;AttachDbFilename=C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\SHOPPROJECT\SHOPPROJECT\shop.mdf;Integrated Security=True;User Instance=True"
Dim ST As String = ComboBox1.SelectedText
Dim sqlcon As New SqlConnection(conectionstring)
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = " & " '" & ST & "'" & "", sqlcon)
MessageBox.Show(TextBox1.Text)
Dim result As Object
Try
sqlcon.Open()
' Dim sdr As SqlDataReader = sqlcmd.ExecuteReader()
result = sqlcmd.ExecuteScalar()
If result IsNot Nothing Then
TextBox1.Text = result.ToString()
MessageBox.Show(TextBox1.Text)
End If
Catch ex As SqlException
MessageBox.Show(ex.Message)
End Try
End Sub
I've tried this, but I can't see the value in the text box, and obbalance is a floating-point value from the SQL database.
If you're updating a text box, is this a single result (scalar value)? If so, the first thing I'd do is use ExecuteScalar not ExecuteReader. Then, use debug mode with breakpoints to get a better idea of what is actually happening. It may simply be that you're not getting any results.
Note: I'm assuming the bad coding practice (in-line sql statement, hard-coded connection string, etc.) are for clarity. If they're not, fix them.
Make the follwing changes:
Dim sqlcmd As New SqlCommand("SELECT OBBALANCE FROM BALANCE WHERE CUSTOMERNAME = '" & ST & "'", sqlcon)
TextBox1.Text = sdr.GetString(yourColumnIndex)
ComboBox1.SelectedText returns the highlighted (selected) text on the ComboBoxControl. That will be empty if you haven't use your mouse to select a portion of its text or hold the shift while you are pressing the direction keys on your keyboard. And that's probably why your query returns ZERO RECORDS.
Use the following instead:
Dim ST As String = ComboBox1.SelectedItem.Text
Set a breakpoint and ensure you are getting the value for OBBALANCE (see if you are getting any rows period might be good). Also, make sure you can only get one row, as you are iterating forward, even when you only need one value.
Better yet, consider ExecuteScalar, which only returns a single value. While you are at it, parameterize the SQL query so you don't get SQL injected.
UPDATE: Just change it here:
sdr = sqlcmd.ExecuteReader()
to something like
Dim s as String = sqlcmd.ExecuteScalar()
Then use s as your textbox value. You may have to ToString() the value or otherwise cast as string, as I believe the ExecuteScalar() returns an object.