Search AutoNumber field in Access via SQL (VB) - sql

I'm trying to allow the 'user' to search for 'members' by searching for their member ID. Here is a screenshot of the database (design view).
https://drive.google.com/file/d/0B7pMpT1WtgKDVU5MVkFYNXJjcTA/edit?usp=sharing
If in VB I search for the ID as an Integer it produces a datatype mismatch error (see below)
https://drive.google.com/file/d/0B7pMpT1WtgKDMFVtYlFiWlpES0E/edit?usp=sharing
Sorry for asking another probably pointless question, thank you though - mean's a lot!

The error lies in this line:
sqlstatement = "Select * from Members where ID = '" + MemberID + "';"
It should be:
sqlstatement = "Select * from Members where ID = " + MemberID + ";"
Since your "ID" field is Autonumber, you're checking condition with a string which is wrong.

You're doing
"WHERE ID = '" + MemberID + "';"
in your VB code. I think this might be your
problem. I guess it thinks the ID is string,
and not int.
I am not very familiar with VB but
try it without the '' i.e. like this:
"WHERE ID = " + MemberID + ";"

Related

double where statement in SQL and ASP

I am a little lost on how to incorporate TWO Where in my sql statement in my asp.
I am trying to get the userID and password entered previously and compare it with what I have in my database created on SQL:
I think my problem comes from my double quotation and single quotation.
UserID is a number in my database and Password is a short text.
var mycon = new ActiveXObject("ADODB.Connection");
var myrec = new ActiveXObject("ADODB.Recordset");
mycon.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\Omnivox.mdb");
var txtpassword = Request.QueryString("txtpassword");
var txtuserID = parseInt (Request.QueryString("txtuserID"));
var sql;
sql = "SELECT UserID, UserPassword FROM UserOmnivox WHERE UserID=" +txtuserID+ " AND UserPassword='" + txtpassword + "';";
myrec.Open(sql, mycon);
thank you
UPDATE: It is still not working. The error massage is : no value given for one or more required parameters for the line myrec.Open(sql,mycon)
Change
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID "AND UserPassword="'+txtpassword';
to
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID + " AND UserPassword='"+txtpassword+"'";
If you'd done any kind of basic debugging, like LOOKING at the query string you're generating, you'd have seen this:
sql = "SELECT [..snip..] UserID=" +txtuserID "AND UserPassword="'+txtpassword
^^--- no space
^--- missing +
which produces
SELECT .... UserID=1234AND userPassword
^^---syntax error, no such field '1234AND'
And then, yes, your quotes are wrong too
sql = "SELECT ... UserID=" +txtuserID "AND UserPassword="'+txtpassword
^------------------^-- one string
^-----------------^-- another string
^---???
It should be
sql = "SELECT * FROM UserOmnivox WHERE UserID=" +txtuserID + " AND UserPassword='" + txtpassword + "';";
I find another more flexible solution is better. Sometimes based on conditions you have one where condition, in others you have zero, and in others you have two. If you go down these paths they don't solve that issue. The following does.....
Some sql query
where 1=1 -- ## A condition that will always be true and does nothing to your query.
and first optional where clause
and second optional where clause
This way if you don't have the first where clause in a given situation but you do have the second you are not missing the words "where". You always have the where and you optionally add any array of "and" parts to your where statement. 100% flexibility in this method works for all challenges. Plus it is easier to follow code once you get past the wtf is this 1=1 nonsense reaction.

Access: Runtime error 3075 (missing operator) in SQL update query

First time using Access and wanted to make an update query that uses a variable for its table name. Now, I've gotten myself into a web of nothing good. When I get to the part the SQL code is needed for, I get Runtime error 3075 - Missing operator in '(((" + enteredid + ".todayDate)=Format(Now()','""Short Date"")))' I've never coded in SQL, so I have no clue what operators are needed.
My code:
strSQL = "UPDATE " + enteredid + " SET " + enteredid + ".signIn = Format(Now(),""Short Time"") WHERE (((" + enteredid + ".todayDate)=Format(Now()','""Short Date"")));"
My suggestions:
You can avoid the whole Format() issue in the WHERE clause by using the Date() function instead of trying to extract just the date part of Now().
Since you are doing an UPDATE on a single table you can just use the field (column) names without the TableName. prefix.
To make your code more robust, enclose the table name in square brackets so it won't crash if the table name contains spaces or other "funny" characters.
So, the revised code would look more like this:
strSQL = _
"UPDATE [" + enteredid + "] SET " + _
"signIn = Format(Now(),""Short Time"") " + _
"WHERE todayDate = Date()"

VB.NET 2010 & MS Access 2010 - Conversion from string "" to type 'Double' is not valid

I am new to VB.Net 2010. Here is my problem: I have a query that uses a combo box to fetch many items in tblKBA. All IDs in the MS Access database are integers. The combo box display member and value member is set to the asset and ID of tblProducts.
myQuery = "SELECT id, desc, solution FROM tblKBA WHERE tblKBA.product_id = '" + cmbProducts.SelectedValue + "'"
In addition to getting items from the KBA table, I want to fetch the department details from the department table, possibly done in the same query. I am trying to do it in two separate queries.
myQuery = "select telephone, desc, website from tblDepartments where tblDepartments.product_id = tblProducts.id and tblProducts.id = '" + cmbProducts.SelectedValue + "' "
All help will be appreciated!
Change the '+' to a '&' then the compiler would be happy.
try adding .toString to cmbproducts.selectedvalue or do "tblKBA.product_id.equals(" & cmbProducts.selectedValue.toString & ")"
1.) Don't use string concatenation to build your query. Use parameters.
2.) I am guessing that tblKBA.product_id is a double and not a string, so don't put quotes around it.
myQuery = "SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = ?"
3 things. Test your value before building the select statement. Second, Use .SelectedItem.Value instead of .SelectedValue. Third, protect yourself from sql injection attack. Use parameters, or at the very least check for ' values.
If IsNumeric(cmbProducts.SelectedItem.Value) = False Then
'No valid value
Return
End If
myQuery = String.Format("SELECT id, desc FROM tblKBA WHERE tblKBA.product_id = {0}", cmbProducts.SelectedItem.Value.Replace("'", "''"))

DELETE FROM table WHERE var = value does not remove entries

So I fetched some data from a mdb file in c# via
"SELECT * FROM " + listBox1.GetItemText(listBox1.SelectedItem) + " WHERE Note = '" + listBox2.GetItemText(listBox2.SelectedItem).Replace("'","\'") + "'";
which selects the right data, here it is
SELECT * FROM Main WHERE Note ='Hello'
The mdb data structure looks like this being plotted as a CSV-file:
"Record ID";Status;Placement;Private;Category;Note;Blob
14341665;4;2147483647;True;3;"""Hello"" - Neues
But when I try to remove entries with
"DELETE FROM " + listBox1.GetItemText(listBox1.SelectedItem) + " WHERE \"Record ID\" LIKE '" + dr[0] + "';";
or
"DELETE FROM " + listBox1.GetItemText(listBox1.SelectedItem) + " WHERE \"Record ID\" = '" + dr[0] + "';";
which looks like for instance
DELETE FROM Main WHERE "Record ID" LIKE '14341665';
The entries just stay there. I can rerun the select command even restart my application, the mdb is not changed.
Is record ID a numeric field? If so, lose the quotes.
DELETE FROM Main WHERE [Record ID] = 14341665;
Note that spaces in field (column) names will always be a problem. Such columns names have to be enclosed in square brackets, as do columns named with reserved words.
The record id is numeric, so don't put apostrophes around it:
"DELETE FROM " + listBox1.GetItemText(listBox1.SelectedItem) + " WHERE \"Record ID\" = " + dr[0]
Note: You should avoid using select * in production code, you should specify the data that you want returned. Also, you should use parameterised queries instead of concatenating values into the query.
if i remember correctly, "like" only works on string data, please check the data type of Record ID.
If Record ID is numeric, you may want to use database's conversion function to convert it into string before filtering using "like".
btw, remember to make sure that dr[0] is properly escaped.

String or binary data would be truncated. The statement has been terminated

I always got an error when adding a new data. the error says
String or binary data would be truncated. The statement has been terminated
As I've looked back on my backend or code. It looks like there's a conflict adding a TWO LABEL DATA in one column because I would like to join the (Year)-(StudentNumber)
Here's the code of my INSERT INTO Statement
INSERT INTO
[Student_Information] (StudentID, LastName, FirstName, MiddleName, Gender,
ContactNumber, Citizenship, Religion, Birthday, Address)
VALUES
( '" & lbl_cyear.Text - studid.Text & "','" + txt_lname.Text + "', '" + txt_fname.Text + "', '" + txt_mname.Text + "', '" + DDGender.Text + "', '" & txt_cnumber.Text & "', '" & txt_citizenship.Text & "' , '" + txt_religion.Text + "' , '" & txt_bday.Text & "', '" & txt_address.Text & "' )"
and here's the code how I generate the Year and the Student Number
Sub SNYear()
Dim test As Date
test = Convert.ToDateTime(Today)
lbl_cyear.Text = test.Year
End Sub
Sub SNGenerate()
'displaying Studentid
Dim SN As Integer ' Student Number
Dim SID As String 'Student ID Num as String
Dim rdr As SqlDataReader
cmd1.Connection = cn
cmd1.Connection.Open()
cmd1.CommandText = "Select Max (StudentID) as expr1 from [Student_Information]"
rdr = cmd1.ExecuteReader
If rdr.HasRows = True Then
rdr.Read()
End If
If rdr.Item(0).ToString = Nothing Then
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
ElseIf rdr.Item(0).ToString = 0 Then
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
Else
SN = rdr.Item(0) + 1
SID = Format(SN, "0000")
End If
studid.Text = SID
cmd1.Connection.Close()
End Sub
Can someone help me with the code? How to join 2 data in different label text and save it to one column in my table.
Woah! Never ever write sql queries like that. It's subject to dangerous SQL injection, and code like that is actually used as worst-case scenarios in SQL injection lectures everywhere!
That being said, the error message String or binary data would be truncated. The statement has been terminated. actually spells out what is wrong. You are trying to insert too much data into a field that has a specific dimension.
You are trying to insert the following expression into the StudentID field:
lbl_cyear.Text - studid.Text
I'm not even sure what you want to do there. Since Visual Basic is loosely typed by default, It will probably handle the lbl_cyear.Text as a number and try to subtract the studid.Text (as a number) from it. You probably mean something like this:
lbl_cyear.Text & "-" & studid.Text
It seems you are trying to use the StudentID column for two different types of information. Don't do that. Decide on one format for the student ids and dimension the column for it.
Is this a homework assignment?
Y#atornblad has some very valid points about re-structuring your code. However, the specific problem you are asking about is likely because you are trying to insert data into a column that is longer than the column can accept.
E.g. - you are trying to insert "Lorem Ipsum" into a column that has a maximum length of 5 characters.
Edit
You need to take another look at how your table is defined and make sure it is appropriate for the data you are storing. Also - make sure the data you are trying to store is in the correct format that the table was designed for. Don't assume it's in the format you want, actually step through the program in debug mode and look at what the variable is before it gets sent to the database.