I'm trying to implement the change password module in a application in VB. The update query is having some issues
Private Sub cmdOK_Click()
Query = "Select * From Users Where LoginID='" & txtLoginID & "' and Password = '" & txtCuPassword & "'"
Set reSet = myCon.Execute(Query)
If (Not reSet.BOF) And (Not reSet.EOF) Then
Query1 = "UPDATE Users SET Password ='" & txtNewPassword & "' WHERE LoginID='" & txtLoginID & "'"
Set reSet = myCon.Execute(Query1)
When executed an error is thrown at UPDATE query, as syntax error.
So, if your code has a single quote in the txtNewPassword field, your query ends up something like this
Query = "UPDATE Users SET Password ='mypass'word' WHERE LoginID='123'"
and this, of course is a syntax error.
You could try to replace a single quote with a pair of single quotes
Query = "UPDATE Users SET [Password] ='" & Replace(txtNewPassword, "'", "''") & "' WHERE ....
But remember that this code is open wide to SQL Injection. You should use parametrized queries also if it is not really easy to do that in VB6. Also, as pointed out by HansUp in its comment, you need to enclose the reserved word Password with square brackets
Why should I use Parameters instead of putting values into my SQL string
Related
I would like to know if there is a way to get system username and use it directly in an MS Access query. I have made a parameter work within a query from a combo box on a form and I have also acquired system name in Access VBA using ENVIRON ("USERNAME").
Kindly let me know if this is possible.
You need to create a VBA function that returns the username, and then use the function in the query.
Public Function GetUserName() As String
' GetUserName = Environ("USERNAME")
' Better method, see comment by HansUp
GetUserName = CreateObject("WScript.Network").UserName
End Function
and
SELECT foo FROM bar WHERE myUserName = GetUserName();
My solution kept all the work in VB.
I used a variable for the windows login username and then created a SQL string with that variable inserted. Lastly, I updated the query behind the form to use this new SQL string.
The CHR(34) puts quotes around the name as it is now a string inside the SQLSTR and needs to be within a set of quotes.
If you have a complex SQL statement, write it in the QBE using a string for the name and all the other variables, then switch to the SQL view and replace it using a VBA variable as shown below.
MyName = Environ("username")
sqlstr = "SELECT * From Projects WHERE ( ((Projects.LeadEngineer)=" & Chr(34) & MyName & Chr(34) & " AND ActiveYN = True ));"
Forms![Main Form].RecordSource = sqlstr
You can use SYSTEM_USER if the query is being executed in a SQL Server, that will retrieve the user name connected to the database (for that, make sure you are not using fixed user name in your connection string)
Yes - you can use the 'CurrentUser' function in your query. Here I've included it as a field and criteria.
SELECT Field1, Field2, [CurrentUser] AS UserName FROM Table1 WHERE Field1 = [CurrentUser];
I have a problem, I'm working on a school project with Visual Basic and I can't manage to fill a dataset with a LIKE query.
I'm using Access in order to manage the database and the query is:
SELECT * FROM VistaProductos WHERE Nombre LIKE "*ta*"
In Access this query is working fine but when I use it on Visual Basic the OleDbDataAdapter fills my DataSet with 0 rows.
Here is the code:
Dim adaptador As New OleDbDataAdapter("SELECT * FROM VistaProductos WHERE " & campo & " LIKE ""*" & valor & "*""", conexion)
adaptador.Fill(dataset, tabla)
Return dataset
campo and valor are variables who have the same data as in the Access example, and I tried by writing them literally too.
The connection to the database is working fine as the other querys work perfectly.
ADO.NET uses the standard % character as wildcard in LIKE expressions.
But your first problem to solve is removing the string concatenations when you build sql queries. You cannot trust your user on this point. If you leave in that way you user can write anything and you risk to pass malicious commands to your database engine. You should always use parameters in these contexts
In your code is present also a field name as a variable part of the query.
This cannot be parameterized, so the only sensible solution is to present your user with a list of field names to choose from
Dim cmdText = "SELECT * FROM VistaProductos WHERE " & campo & " LIKE #valor"
Dim adaptador As New OleDbDataAdapter(cmdText, conexion)
adaptador.SelectCommand.Parameters.Add("#valor", OleDbType.VarWChar).Value = "%" & valor & "%"
adaptador.Fill(dataset, tabla)
Return dataset
I used this line
.RecordSource = "select * from tblpersonal where empid like '" & Me.lblIDNumber.Caption & "*'"
...my question is, what if I use a variable (varIDNumber) instead of object (lblIDNumber), what would be the syntax? I am using VB6.0
You didn't mention txtIDNumber in the code -- you mentioned lblIDNumber. I assume you mean for those two to be the same. In other words, the code you have at present should be something like this:
.RecordSource = "select * from tblpersonal where empid like '" & Me.txtIDNumber.Text & "*'"
So you are using the value of a text box in a form to populate the SQL query. Am I right so far?
And you are asking, what if I store the ID number in a variable rather than a text field? I agree, this is probably a step in the right direction.
So you might create a variable in the "General Declarations" section of the form using:
Dim idNumber As Integer
With the idea being to update the value of that variable each time the text field changes. Note: I am assuming that the "ID number" is an integer -- if not, you should use a String instead.
Now you need to update that variable when the text field changes. In the txtIDNumber_Change event, you will want to add code to convert the string txtIDNumber.Text into an Integer, and store it in idNumber. I forget the exact syntax, but I am guessing something like:
idNumber = Int(txtIDNumber.Text)
Finally, you can now use the idNumber variable in the SQL query rather than the text box:
.RecordSource = "select * from tblpersonal where empid like '" & idNumber & "*'"
Replace Me.lblIDNumber.Caption with varIDNumber
If you have a constant in the label and would prefer for the constant to be stored in a variable instead, create a Const in the form's code. Let's say the label has the text "43" in it.
In the general declarations section of the form, add the code:
Const idNumber As Integer = 43
Then, when constructing the query:
.RecordSource = "select * from tblpersonal where empid like '" & idNumber & "*'"
This will construct the query using the constant 43. I don't really see the point of this -- if you want the employee number to be something the user can type in, see my other answer.
I know that there's something wrong with my syntax... "select * from tblpayroll where empid = userid"
UserID is a variable...
apparently, it's your vb variable.
select * from tblpayroll where empid = '" & userid & "' "
use it this way, and it'll work
The text "select * from tblpayroll where empid = userid" will be sent through exactly as is to the SQL back end, the userid part will not be substituted. So, unless you have a userid column, you'll probably get an error. Even if you do have a userid column, the results won't be what you expect.
What you need to do depends on whether userid is a numeric or string value. For numerics, you can use:
"select * from tblpayroll where empid = " & CStr(userid)
This will first turn the numeric value into a string and check it as-is.
For string values, use:
"select * from tblpayroll where empid = '" & userid & "'"
This will simply surround the string with quotes to ensure a string comparison works. You need to be aware that this is a bad idea if userid has not been sanitised somehow - it may lead to SQL injection attacks. The art of fixing that is outside the scope of this particular question but it's worth keeping in mind.
What to do if your variable is numeric but the database field is a string is another matter. You can do it with CStr and zero-padding but, since it's an unlikely scenario, I haven't documented it here.
How can I use Linq with Dataset.xsd files?
I've looked at Linq-to-Datasets and Linq-to-XSD but they don't really seem to work directly with the Visual Studio DataSet.xsd files.
EDIT: I actually found a great link for this: link text but I can't seem to figure out what to do if I want to query on related tables.
Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
Dim fields = taFields.GetData()
Dim results = From f In fields Select f
For Each field In results
Response.Write(field.FieldID & " " & field.Label & " " & field.FieldTypeRow.FieldTypeLabel)
Next
I get an "Object reference not set to an instance of an object." error when running the above code because, I guess, field.FieldTypeRow.FieldTypeLabel isn't actually part of the query of data. Do I have to create a method that returns data from that data also? I'm assuming this would be the case (that taFields.GetData has to return all the FieldType data results too if I'm going to reference it - in Linq to SQL it does all this for me so it's a little disappointing)
A DataSet is just a container for your data, so you need to fill it first. LINQ to SQL will create SQL and go to the database for you...but when you're working with DataSets, you're using LINQ to Objects, which won't create SQL. So you need to make sure that all tables you need in the DataSet are filled before you start writing LINQ to query your DataSet.
I think you're looking for something along these lines:
Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
Dim taFieldTypes As New TestDSTableAdapters.FieldTypesTableAdapter()
Dim ds As New TestDS
taFields.Fill(ds.Fields)
taFieldTypes.Fill(ds.FieldTypes)
Dim results = From f In ds.Fields Select f
For Each field In results
Response.Write( _
field.FieldID & " " & field.Label & " " &
field.FieldTypeRow.FieldTypeLabel)
Next
Dim taFields As New TestDSTableAdapters.FieldTableAdapter()
Dim fields as TestDSTableAdapters.FieldsDataTable = taFields.GetData()
Dim results = From f In fields Select f
For Each field In results
Response.Write(field.FieldID & " " & field.Label & " " & field.FieldTypeRow.FieldTypeLabel)
Next
You forgot to set the type for fields. That is why yo uwere getting object reference problems. You do not have to create a new blank dataset.