I'm trying to display the results of a simple SQL sum... I have the following SQL command on my .asp page using vb:
<%
Dim QtyTotal
QtyTotal = "SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations"
Response.Write(QtyTotal)
%>
The output (QtyTotal) is written as the SQL statement itself and not the value.
Try adding something like this to connect to your database and to run your query.
Dim con As SqlConnection = New SqlConnection("Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MyDB.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True")
Dim cmd As SqlCommand = New SqlCommand("SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations", con)
con.Open()
cmd.ExecuteNonQuery()
con.Close()
There are tons of articles out there on how to do this, please refer to google.com
You have this value:
"SELECT SUM(Qty_SAL) FROM dbo.tbl_stock_at_locations"
That's just a string literal. Nothing more. Assigning it to QtyTotal just means the variable is a string with the SQL command text as it's value.
If you want to run the statement and get the result, you need to create an ADO.Connection object to the connect to a database server, create an ADO.Command object to hold your SQL statement, and associate the command with the connection. Then you can .Open the connection and .Execute the command to get an object back for reading results... the kind of object will depend on how you execute the command. Once you have this object, you have to actually read from it to assign the final value to QtyTotal.
Related
I am running an Access update query in VB.Net.
dbCustSpec_ADO.Execute("table_upt")
Ir runs fine except for the following "Update to" statement
[table].[field1] & [table].[field2]
The following is working properly
[table].[field1]
So does the following
[table].[field2]
It is only when I concatenate both fields when VB.Net throws an error:
System.Runtime.InteropServices.COMException: 'Invalid SQL statement; expected 'DELETE', 'INSERT', 'PROCEDURE', 'SELECT', or 'UPDATE'.'
Btw: The concatenation works properly when calling the query in Access.
My question is:
How can I concatenate both fields in order to make it run while calling it from VB.net
It not clear, are you using the .net oleDB provider here?
Or are you creating a instance of the Access database engine?
You better off to use oleDB such as this:
Imports System.Data.OleDb
And then your code to update can look like this:
Using conn As New OleDbConnection(My.Settings.TESTAce)
Dim strSQL As String = "UPDATE tblHotels SET FullName = FirstName + ', ' + LastName"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
cmdSQL.ExecuteNonQuery()
End Using
End Using
And if you wanted to ran a "existing" update query in Access?
They are considered store procedures. Say we have upate query saved in Access called
qryFirstLast
Then the above code to run that query would be:
Using conn As New OleDbConnection(My.Settings.TESTAce)
Dim strSQL As String = "qryFirstLast"
Using cmdSQL As New OleDbCommand(strSQL, conn)
conn.Open()
cmdSQL.CommandType = CommandType.StoredProcedure
cmdSQL.ExecuteNonQuery()
End Using
End Using
Note how we set the command type = StoredProcedure.
I'm trying to take a Yes/No value from my database on Access and make it so if the Yes/No is checked on Access it will check it on the form. Although I keep getting
System.Data.OleDb.OleDbException: 'No value given for one or more required parameters.'
On the line Dim rs As OleDbDataReader = SQLCmd.ExecuteReader()
Sorry if it's a really easy and stupid mistake, I'm a college student and googling isn't helping me figure this one out.
cn.Open()
Dim SQLCmd As New OleDbCommand
SQLCmd.Connection = cn
SQLCmd.CommandText = "SELECT *, staffIn FROM Staff WHERE staffName = DarrenSloan"
Dim rs As OleDbDataReader = SQLCmd.ExecuteReader()
While rs.Read
Dim DisplayValue As String = rs("staffIn")
SQLCmd.Parameters.AddWithValue("#inorout", inOrOut.Checked)
SQLCmd.ExecuteNonQuery()
End While
cn.Close()
I know this is an old post but I seem to remember that OleDb does not support named parameters.
Also, pretty sure that DarrenSloan should be surrounded by single quotes, like any string value. And indeed, reusing the SQL command like this is not the way to do it.
The CommandText:
SQLCmd.CommandText = "SELECT *, staffIn FROM Staff WHERE staffName = DarrenSloan"
does not contain any parameter.
Thus, the parameter inorout has no effect:
SQLCmd.Parameters.AddWithValue("#inorout", inOrOut.Checked)
Either use two statements, one SELECT and one UPDATE.
Or use a different mechanism like a databound grid. Maybe you are using a datagridview control to display the data. Then there are different techniques to keep the data in sync. It depends on how you choose to render the data on your form.
Firstly, get rid of the loop. You would only use a loop if you were expecting more than one record. By the looks of it, you are expecting only one record, so no loop.
Secondly, stop calling ExecuteNonQuery. That is for making changes to the database, which you're obviously not trying to do. You obviously know how to get data from the query because you're doing it here:
Dim DisplayValue As String = rs("staffIn")
If you want to get data from another field, do the same thing. You can then use that data in whatever way you like, e.g.
Using connection As New OleDbConnection("connection string here"),
command As New OleDbCommand("SELECT * FROM Staff WHERE staffName = 'DarrenSloan'", connection)
connection.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
Dim inOrOut = reader.GetBoolean(reader.GetOrdinal("inorout"))
inOrOutCheckBox.Checked = inOrOut
End If
End Using
End Using
Notice that I have wrapped the text literal in the SQL in single-quotes? I would expect that you would normally not want to hard-code a name there, but use input from the user instead, In that case, you would use a parameter, e.g.
Using connection As New OleDbConnection("connection string here"),
command As New OleDbCommand("SELECT * FROM Staff WHERE staffName = #staffName", connection)
command.Parameters.Add("#staffName", OleDbType.VarChar, 50).Value = staffNameTextBox.Text
connection.Open()
Using reader = command.ExecuteReader()
If reader.Read() Then
Dim inOrOut = reader.GetBoolean(reader.GetOrdinal("inorout"))
inOrOutCheckBox.Checked = inOrOut
End If
End Using
End Using
I am new to this forum, please could you help me get this code to work, when i execute it, it simply does nothing and does not update the DB. If i remove the square brackets it gives an error: "SYNTAX ERROR in UPDATE statement"
Any help appreciated!
Dim connection As OleDbConnection
connection = New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=UserDB.accdb;Jet OLEDB:Database;")
connection.Open()
Dim pass As String
pass = txtconfirm.Text
Dim user As String
user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= '" & pass & "' WHERE [Username]= '" & user & "';"
Dim command As New OleDbCommand(query, connection)
command.ExecuteNonQuery()
connection.Close()
Given your actual connection string, the database that will be updated is the one in the directory where your application starts. This means that if you work with a WinForms application this folder is \BIN\DEBUG or x86 variant. If there is not error then you could get the return value of the ExecuteNonQuery call to verify if a record has been updated or not
Dim rowsUpdated = command.ExecuteNonQuery()
MessageBox.Show("Record updated count = " & rowsUpdated)
If this value is not zero then your database has been updated and you are looking for changes in the wrong database. Check the one in the BIN\DEBUG folder.
In any case your code has big problems. If your variables user or pass contain a single quote, then your code will crash again because your string concatenation will form an invalid SQL. As usual the only workaround is to use a parameterized query
Dim pass = txtconfirm.Text
Dim user = LoginForm.UsernameTextBox.Text
Dim query As String = "UPDATE [Users] SET [Password]= #p1 WHERE [Username]= #p2"
Using connection = New OleDbConnection("...........")
Using command As New OleDbCommand(query, connection)
connection.Open()
command.Parameters.Add("#p1", OleDbType.VarWChar).Value = pass
command.Parameters.Add("#p2", OleDbType.VarWChar).Value = user
command.ExecuteNonQuery()
End Using
End Using
The parameterized approach has many advantages. Your query text is more readable, there is no misunderstanding between your code and the values expected by your database engine. And while not easy to exploit with MS-Access there is no problem with Sql Injection
I think Steve presents a much better approach for you coding this...
Let me just throw out a few more things:
The reason you can't take those brackets out is some of your column names are reserved words; just FYI.
Since you report "it does nothing..." when you execute, it sounds like you have a valid connection and sql syntax, in which case my next step would be to copy the sql command text while in debug mode, change it to a select and run it in your DB. You should get one result when you do. If not, either your criteria or field contents are not what you think they are...
Just change the Update table SET field-value ... to SELECT * FROM table and leave the WHERE clause as is.
I am attempting to insert a single record into an SQL Server 2012 database, programmatically, using a small VB.net application. When I execute the application, the following OleDBException is caught:
Undefined function 'convert' in expression
My VB looks like this:
Dim conn As OleDbConnection = New OleDbConnection(connstring)
Dim comm As OleDbCommand = New OleDbCommand(insertcommand)
comm.Connection = conn
Try
conn.Open()
comm.ExecuteNonQuery()
Catch ex As Exception
txbErrorSummary.Text += ex.ToString()
End Try
Where insertcommand looks like:
INSERT INTO XXX([JCN], [DOT])
VALUES('PD7654',convert(varchar, '2/17/2014', 101))
Interestingly, when I cut and paste the insertcommand into the SQL Management Studio, it inserts the record with no trouble. Thoughts?
Appreciate the help
I will suggest you to do this other way. Instead of trying to run convert inside SQL, do this in .NET application and pass already DateTimem object.
The probelm with convert function is that it is not an OleDB valid function. If you use SqlCommand it will probably works correctly, because this function is T-SQL valid only for MS SQL
I am a complete beginner to .net and am confused at some basic things. Please help.
First of all the table I create and populate (by right clicking tables in server explorer) disappear once I restart the computer. how do I keep them.
Is there any better place/interface to type SQL queries in vb.net than the command prompt.
In the following code:
Dim cn As SqlConnection = New SqlConnection(strConnection)
cn.Open( )
' Create a data adapter object and set its SELECT command.
Dim strSelect As String = _
"SELECT * FROM Categories"
Dim da As SqlDataAdapter = New SqlDataAdapter(strSelect, cn)
' Load a data set.
Dim ds As DataSet = New DataSet( )
da.Fill(ds, "Categories")
This far the code runs fine but just to gain better understanding, I would like to ask that
while data from SQL Server database was saved into da in accordance to the query, why do we need to save/transfer it in the dataset object ds.
Is there any additional benefit of SqlCommand over SqlDataAdapter besides speed?
Dim autogen As New SqlCommandBuilder(da)
Dim dt As DataTable = ds.Tables("Categories")
' Modify one of the records.
Dim row As DataRow = dt.Select("CategoryName = 'Dairy Products'")(0)
row("Description") = "Milk and stuff"
gives an error when I use it with
da.Update(ds, "Categories")
regarding dt.select not returning any value.
What is the way out?
to answer your questions :
The tables you create with the server explorer are IN MEMORY. Same goes for dataset, they are in-memory representation of your table. As for your 2nd example, the DS you use isnt filled when you try to get the DT. hence why the DT is empty.
If your starting, I would suggest you go look into Linq-to-Sql (http://msdn.microsoft.com/en-us/library/bb425822.aspx) for a more up-to-date way of doing sql in .net ( I think its 4.0 framework)
As for the 2nd point, I'd say normally you should use store procedure for most of your sql commands .. the sqlcommand is use like this
Try
Cmd = New SqlClient.SqlCommand("st_InventoryStatus_Or_AnyStoreProcName_Or_ASqlQuery")
Cmd.CommandTimeout = 300 'not really needed'
Cmd.CommandType = CommandType.StoredProcedure 'you can type CommandType.Text here to use directly your "Select * from Category"'
Cmd.Parameters.Clear() 'just to be sure its empty, its not mandatory'
Cmd.Parameters.Add("#idCategory", SqlDbType.Int).Value = myCategory.Id 'here are the parameters of your store proc, or of your query ("select * from Category where Category.id = #Id")'
Catch ex As Exception
MsgBox(ex.Message, MsgBoxStyle.Information)
End Try