Data adapter troubles - sql

When I run the code the line which filled my datatable says that there is no value given for one or more parameters
Order = New OleDb.OleDbDataAdapter("SELECT * FROM Orders WHERE
Driver_ID = " & ID, DBREF)
Order.Fill(dataODtable)
DGVorders.DataSource = dataODtable
The code says this:
An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll
Below is an image link to the database and table it is referencing.
(Database orders table)
If I try run the code without the where statement it runs without crashing.

The field DRIVER_ID is clearly a string, as such you need single quotes around the value you want to use for the WHERE clause.
But that would be wrong for a long list of reasons (Sql Injection, Parsing errors, automatic type conversion with incompatible locales).
So you really need to start using parameterized queries as soon as possible to avoid these misteps
Dim cmdText = "SELECT * FROM Orders WHERE Driver_ID = #drvID"
Order = New OleDb.OleDbDataAdapter(cmdText, DBREF)
Order.SelectCommand.Parameters.Add("#drvID", OleDbType.VarWChar).Value = ID
Order.Fill(dataODtable)
DGVorders.DataSource = dataODtable
Now the query is no more built concatenating together strings pieces (the main source for sql injection hacks) but you create a parameter object of the correct type and pass it to the database engine that will use it when needed.
Another benefit is the more clear code you get. In this case perhaps is not very evident but with more complex queries you will have a more clear understanding of what you are asking to do to the database.

You can try like this:
Order = New OleDb.OleDbDataAdapter("SELECT * FROM Orders WHERE
Driver_ID = '"& ID &"'", DBREF)
Order.Fill(dataODtable)
DGVorders.DataSource = dataODtable
maybe this will be the problem.

if Driver_ID is alphanumeric column, select query should be SELECT * FROM Orders WHERE Driver_ID = '" & ID & "' ;"

Related

Date MS access vb.net

I want to update an item's expiration date in MS access but It throws a data type mismatch
This is the code I used to update the item please check this Thanks I tried doing addwithvalue and add("expD",oledbtype.Date) Non works
Query
query = "Update Medicines set BarcodeID = #BarcodeID, Drugs =#DrugName, Dosage = #Dosage, Quantity= #Quantity, Station =#Station, ExpD =#ExpDate, Price=#Price, stckid=#stckid, IsActive='" & ComboBox1.Text & "' where BarcodeID=#BarcodeID"
My parameters
cmd.CommandText = query
cmd.Parameters.AddWithValue("#BarcodeID", txtbarcode.Text)
cmd.Parameters.AddWithValue("#DrugName", txtdrugs.Text)
cmd.Parameters.AddWithValue("#Dosage", txtdosage.Text)
cmd.Parameters.AddWithValue("#Quantity", txtquantity.Text)
cmd.Parameters.AddWithValue("#Station", txtstation.Text)
cmd.Parameters.AddWithValue("#Price", txtprice.Text)
'cmd.Parameters.Add("#ExpD", OleDbType.Date)
'cmd.Parameters.AddWithValue("#ExpDate", dtExpD.Value.Date)
cmd.Parameters.Add("#ExpDate", OleDbType.Date).Value = Me.dtExpD.Value.Date
cmd.Parameters.AddWithValue("#stckid", txtstockid.Text)
cmd.Parameters.Add("#IsActive", OleDbType.LongVarChar)
cmd.Parameters("#IsActive").Value = combocontainer
Thanks
Even though you are using parameter names in your SQL code, the Jet and ACE OLE DB providers ignore those names and substitute values from parameters into the SQL code based on position. That means that you MUST add the parameters to the command in the same order as they appear in the SQL code. You ought to do that regardless but it is essential for Access databases. Your SQL code contains "ExpD =#ExpDate, Price=#Price" but you add parameters like this:
cmd.Parameters.AddWithValue("#Price", txtprice.Text)
cmd.Parameters.Add("#ExpDate", OleDbType.Date).Value = Me.dtExpD.Value.Date
The order is reversed so those values are actually getting used the wrong way around. At least you were alerted by the data type mismatch. If they had been the same type then it would have worked but saved the wrong data to the wrong columns.

insert into sql statement - asp classic - no value given -

I am working with asp classical.
I am trying to take information from the user and then insert into my database.
the error is "no value given".
on line: myCon.Execute(sql);
I think it is coming from my sql statement.
var myCon, myRec, sql;
myCon = new ActiveXObject ("ADODB.Connection");
myCon.Open ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\abc.mdb");
var bodyType = parseInt(Request.Form("cbBodyType"));
var education = parseInt(Request.Form("cbEducation"));
var eyes = parseInt(Request.Form("cbEyes"));
var hairs = parseInt(Request.Form("cbHairs"));
var heights = parseInt(Request.Form("cbHeights"));
var religion = parseInt(Request.Form("cbReligion"));
var memberID = parseInt(Session("MemberID"));
sql = "INSERT INTO Profiles (MemberID, Religion, HairColor, Eye, Education, Height, BodyType) VALUES ("+memberID+", "+religion+", "+hairs+", "+eyes+", "+education+", "+heights+", "+education+")";
myCon.Execute(sql);
myCon.Close();
EDIT: The problem is the logic. I have for example table HairColor that has an ID and a Description. ID is a primary key and its foreign key is in table Profile.
When my user enters the information, i would like to recuperate the combobox value, get the ID and then do an INSERT INTO PROFILES.
Is there an easy way to do it instead of using a lot of "where statement" ?
Try the use the following variant of code
myCon.Execute sql, 0
(without parenthesis)
My guess is that one of the following is happening:
One of the columns you are trying to populate could be a string-valued column. In that case, you need to surround your value argument with single quotes, as in this simplified-for-clarity example below:
sql = "INSERT INTO Profiles (MemberID, Religion) VALUES (" _
+ memberID + ",'" + religion + "');"
Alternatively, if you have a - All - or Please Select option as the top and default option in one of your combo boxes, and you haven't specified a value for that option, you could be returning a blank/empty string as a value. That would lead to this as the resulting (simplified-for-clarity) SQL:
Sql = "INSERT INTO Profiles (MemberID, Religion) VALUES( 235, );"
Note the absence of a value for the second column. I would have expected you to get a syntax error message instead, though, if that's what was happening.
Be aware that by doing your SQL this way, assembling a string from posted values rather than using SQL parameters, you are opening the door for a SQL injection attack. It's not a good idea.

Saving a SQL result that has multiple data being read from a Microsoft Access database

I'm trying to send a email with multiple data from an SQL statement but I can't get the result of the SQL statement to be saved in the variable.
str = "SELECT Test.*,TestTopicScore.[Easy Question Score],TestTopicScore.[Medium Question Score],TestTopicScore.[Hard Question Score] from Test INNER JOIN TestTopicScore on Test.TestID = TestTopicScore.TestID ORDER BY Test.Score DESC"
mycommand = New OleDbCommand(str, myconnection)
myReader = mycommand.ExecuteReader
myReader.Read()
emailcontents = myReader("emailcontents")
The connection with the access database is fine and the data is read but i just cant get it to save in a variable.
The error I get:
An unhandled exception of type 'System.IndexOutOfRangeException' occurred in System.Data.dll
Additional information: emailcontents
Let's look at your query first, I've formatted it a bit to make it easier to see what's going on:
SELECT Test.*
,TestTopicScore.[Easy Question Score]
,TestTopicScore.[Medium Question Score]
,TestTopicScore.[Hard Question Score]
FROM Test
INNER JOIN TestTopicScore
ON Test.TestID = TestTopicScore.TestID
ORDER BY Test.Score DESC
What that is doing is selecting several different fields, not one value. Your code emailcontents = myReader("emailcontents") attempts to read one field which is named "emailcontents". Unfortunately, there is no such named field.
It is worse than that: you don't even know how many fields Test.* is going to return.
So, start by enumerating every field which you want from Test.
Then, you appear to want just one string as the result, so you will need to concatenate the fields as strings instead of returning them separately.
In Access, the operator to join strings together is &, and it should convert numeric values into strings for you, thus:
SELECT Test.SomeField & Chr(13) & Chr(10)
& Test.SomeOtherField
& Test.AnotherField
& TestTopicScore.[Easy Question Score]
& TestTopicScore.[Medium Question Score]
& TestTopicScore.[Hard Question Score]
AS [emailcontents]
FROM Test
INNER JOIN TestTopicScore
ON Test.TestID = TestTopicScore.TestID
ORDER BY Test.Score DESC
Notice how I put & Chr(13) & Chr(10) between Test.SomeField and Test.SomeOtherField: that puts in a new line between the two. You might want to do it in between all the fields.
Also, I gave a name to the concatenated data with AS.
Now we're getting into really messy stuff by having to put the formatting of the output into the database. You don't want to do that. Let me emphasise this so it stands out: A better way is to read all the fields individually in your VB.NET code and format them into a string there.
ETA: Not only all that, but it looks like you might return more than one set of results (from seeing the ORDER BY), in which case you will have to read all the results in a loop.

Syntax error with Date in sql query

In my program I'm saving date from DateTimePicker into the global variable with
My.Settings.date = dtpDate_do.Value.Date. I'm using this date to compare date from my database but I'm always getting syntax error, no matter what I'm changing.
This is my query:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = " & My.Settings.date & " ORDER BY ID DESC"
Dates in my database are stored in EU format with dots - 17.2.2014. Can anyone provide me some help.
Never ever create your query like that. Always and without any exception use parameters. This avoids both SQL-injection attacts and ensures proper formatting of your parameters.
Sorry for not knowing VB.NET, but it should be similar to this:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = #Date ORDER BY ID DESC"
cmd.Parameters.AddWithValue("#Date", My.Settings.data)
Explanation: Create your query using #ParamName as a placeholder for your parameters. Then substitute your parameters with values. Make sure to either apply a concrete typed value (i.e. not an object) or/and supply the data type otherwise.
Try to use a parameter in the query like this:
cmd.CommandText = "SELECT ID, order_date FROM orders WHERE order_date = #date ORDER BY ID DESC";
cmd.Parameters.Add(new SqlParameter("#date", dateTimePicker.Value.Date));

Input string was not in a correct format Error Filling a Datatable

I have a table which is all VarChar() fields.
I fill the dataset with the following SQL (using vb.net):
Select * From archive_naerns90_2006_q3.NAERNS90_Calls Where siteid = 'NAERNS90-02-627303'
I get this error:
Input string was not in a correct format.Couldn't store <02-627303> in agencyid Column. Expected type is Double.
When I run this query from PgAdmin it works fine. I am running this same bit of code on dozens of other tables with no problems.
The value 02-627303 referenced in the error is the value in the agencyid column for that record, but there are no Double fields in the table. Full disclosure - there were two, but I changed them from Double to VarChar and neither were the agencyid coplumn.
The other kicker is this only happens on some records in that table.
I am guessing I have some corrupt table. I copied the table, but the copy has the same problem. And Since it works in PgAdmin but not from my code it also may have something to do with npgsql.
Edit: I was asked to add the code around the problem area as this looked like an Insert error. I am not doing any Inserts at all in this function.
SQL = "Select * From " & MlocRow("currentdb") & "." & SubTablesArr(Y) & " Where siteid = '" & DataRow("siteid") & "'"
Adapter.SelectCommand = New NpgsqlCommand(SQL, MLConnect)
Adapter.Fill(subDT)
My ConnectionString is:
"HOST=192.168.0.133;DATABASE=masterlists;USER ID=myuser;PASSWORD=mypassword"
Thanks,
Brad
You can type cast that col to varchar() explicitly...