how to update null visual basic.net 2012 ,,,
sql="Update mytb set name='' where no_ktp='"& sed.text &"' "
that's cannot
HElp me please . its form my job school
If you wanted to update a tables where a certain value was present, you should use something like the following :
Dim sql = "UPDATE mytb SET name = NULL WHERE no_ktp = #sed"
Use Parameterization, Not Concatenation When Building Queries
You should not be building your database queries like this. It is going to leave you prone to issues with incorrect syntax and possible SQL Injection attacks.
Instead consider adopting an approach like the following that takes advantage of SQL Parameterization and should help avoid issues similar to those previously mentioned :
' Build a Connection to use '
Using connection = New SqlConnection("{your-connection-string}")
' Open your connection '
connection.Open()
' Build your query (using parameters) '
Dim query = "UPDATE mytb SET name = NULL WHERE no_ktp = #sed"
' Build a command to execute '
Using command = New SqlCommand(query, connection)
' Add your parameters '
command.Parameters.AddWithValue("#sed", sed.Text)
' Execute your update '
command.ExecuteNonQuery()
End Using
End Using
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 have a list of Users Names in ComboBox and Some TextBoxes. When ComboBox text changes (i.e I select some username from ComboBox), The TextBoxes are filled with user details from the database.
I have code to achieve this in SQL Database. But these queries are not working with MsAccess database.
MysqlConn = New MySqlConnection
Mysql.ConnectionString = "server=localhost;user=root;password=root;database=database"
Dim READER As MySqlDataReader
Try
MysqlConn.open()
Dim Query As String
Query("select * from database.usernames where name='" & ComboBox1.Text & "'")
Command = New MySqlCommand(Query, MysqlConn)
READER = Command.ExecuteReader
While READER.Read
TextBox1.Text = READER.GetString("name")
End While
End Try
Here is my answer. Please don't get overwhelmed by it. ;)
Broken code
First of all, as I see it, the code you provided cannot work at all, because:
your Query variable is initialized in an invalid (or at least a very exotic) way. You probably want to use something like:
Dim Query As String
Query = "select * from database.usernames where name='" & ComboBox1.Text & "'"
or in a single line:
Dim Query As String = "select * from database.usernames where name='" & ComboBox1.Text & "'"
you try to assign the connection string to the ConnectionString property of a nonexistent Mysql variable. Or the variable exists because it is declared somewhere else, which might be a bug in your code snippet here. But I assume you want to assign the connection string to the MysqlConn.ConnectionString property instead.
you have not declared the MysqlConn and Command variables anywhere. You only just assign to them. (I will simply assume you have declared the variables correctly somewhere else in your code...)
the IDataRecord interface does not provide a GetString(name As String) method overload. So unless you have defined a custom extension method for it, you probably need to use the IDataRecord.GetOrdinal(name As String) method as well, or use the column index instead of the column name.
Anyway, the code you provided uses MySQL. So I assume that MySQL is the "SQL Database" you are using successfully. And that seems to work, as you say? Well... Hmmm... Then I will simply assume your code snippet is completely correct and works perfectly with MySQL... :/
MS Access vs. MySQL
Using MS Access requires other data access classes (probably the ones in namespace System.Data.OleDb) and another connection string. You could take a look at this ADO.NET OleDb example for MS Access in the Microsoft documentation.
You probably even have to update your SQL query, because every database system uses its own SQL dialect. You might want to consult the Office documentation for that. But your query is quite simple, so perhaps all you have to do to make it work with MS Access is:
remove the database name and use only the table name, and
delimit the name identifier (since it is a reserved keyword in MS Access).
I personally delimit all identifiers in my SQL queries, just to avoid unintended conflicts with reserved keywords. So I would personally use something like this:
select * from [usernames] where [name] = '...'
Additional tips
Also, I would like to provide you some additional (unrelated) tips regarding improving your code:
Use Using-statements with variables of an IDisposable type as much as possible. Those types/classes do not implement that interface if there isn't a good reason for it, so I consider it not unimportant to call Dispose when you are done with such disposable objects (or using a Using statement to call Dispose implicitly).
Use SQL parameters (if possible) to avoid SQL injection vulnerabilities. Look at this StackOverflow question and its answer for an example of how to use SQL parameters with MS Access.
Example
You may take a look at the following code snippet. It might not provide a working example out-of-the-box, but you might get some useful/practical ideas from it:
Dim connectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Data\\database.mdb;User Id=admin;Password="
Dim query As String = "select * from [usernames] where [name] = #Name"
Using conn As New OleDbConnection(connectionString)
Using command As New OleDbCommand(query)
command.Parameters.Add("#Name", OleDbType.VarChar, 50).Value = ComboBox1.Text
conn.Open()
Using reader As OleDbDataReader = command.ExecuteReader
If reader.Read Then
textbox1.Text = reader.GetString(reader.GetOrdinal("name"))
End If
End Using
End Using
End Using
Using OLEDB and SQl to interact with an access database, and I need to update one column of the database however there is an error
This is made in vb.net.
I have made sure they are being set in the correct order based off of my database
Dim sql As String = "UPDATE UserInfo SET Password=?, CurrentLevel=? WHERE Username=?" & LoggedInUsername 'TheSQL/DDL code to update
Dim comd As New OleDb.OleDbCommand(sql, Connstring) ' create a COMMAND for this SQL
'set up all the parameters needed but they must be set in the same order as used in SQL
MsgBox(Dlevel & " 1 Is Working")
' comd.Parameters.AddWithValue("#Username", LoggedInUsername)
comd.Parameters.AddWithValue("#Password", LoggedInPassword)
comd.Parameters.AddWithValue("#CurrentLevel", Dlevel)
MsgBox(Dlevel & " 2 Is Working")
comd.ExecuteNonQuery() 'Execute the command
It should update the database to change the Current Level. I have used message boxes to find where the problem is and it is when the command is being executed
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 have a fairly complicated SQL query with a nested subquery. When I try to use parameters in Microsoft Query is say I can use parameters in queries that cant be represented graphically. So I need another option. I think you can place your SQL query in a cell as a string then have a Macro run it. Any ideas how I could do this?
Thanks
-Jesse
Here's what I do to work around the limitations of Microsoft Query in Excel 2007:
A produce a dummy query (SELECT NULL AS Test, for example) in Microsoft Query and insert it into the worksheet.
Right-click on the table that MS Query just inserted and click Table->Edit External Data Properties.
Click on the Connection Properties button, then click the Definition tab.
In the Command Text section, write out or paste in the query that you want, using the usual '?' convention for parameters, then click OK.
Click OK to exit the External Data Properties window.
Right click on the table again, and select Table->Parameters to bind the parameters in the usual way.
The idea is the bypass the GUI that MS Query provides, which has some arbitrary limitations that the underlying engine does not.
This works for many complex queries, but not all. When I encounter a query that MS Query refuses to digest at all, I either refactor the query (when feasible) or create a VIEW on the SQL server and query against that.
Another way to solve this is to use stored procedures
CREATE PROCEDURE [dbo].[yourprocedure] #DATEFROM DATETIME, #DATETO DATETIME
AS
SELECT Query
where date >= #datefrom
and date <= #dateto
then on the table properties click Connection Properties button, then click the Definition tab. In the Command Text section:
EXEC yourprocedure #DATEFROM = ?, #DATETO = ?
and direct the ? to the cells you want
Unfortunately the ? doesn't work for most of my queries and a lot of them are not necessarily suited to being turned into views.
The main alternative I use is getting a macro to return the code
Dim Con As New ADODB.Connection
Dim RS As New ADODB.Recordset
Dim server, Database As String
Dim Data as Worksheet
Set data = ThisWorkBook.Worksheets("data")
'rename field here and elsewhere to your variable eg SD or StartDate
Dim field as string
server = "servername"
Database = "database"
'set connection string
If Con.State <> 1 Then
Con.ConnectionString = "Provider=SQLOLEDB;Data Source=" & server & ";Initial Catalog=" & Database & ";Integrated Security=SSPI;"
'this is just setting the connection time out to infinite
setcono:
Con.ConnectionTimeout = 0
Con.CommandTimeout = 0
'this is making sure it set the connection time out to infinite
If Con.ConnectionTimeout > 0 Then GoTo setcono
If Con.CommandTimeout > 0 Then GoTo setcono
Con.Open
Set oRS = New ADODB.Recordset
oRS.ActiveConnection = Con
field = Range("A2").value
oRS.Source = "YOUR SQL QUERY "
oRS.Source = oRS.Source & " WHERE field = '" & field & "'"
oRS.Open
data.Range("A2").CopyFromRecordset oRS
End If
oRS.Close
Con.Close
If Not oRS Is Nothing Then Set oRS = Nothing
If Not Con Is Nothing Then Set oCon = Nothing
I would love Microsoft to fix the bug where it returns errors for the more complex queries as I find it frustrating creating macros just for the sake of returning a simple dataset