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

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.

Related

Data adapter troubles

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 & "' ;"

SqlCommmand parameters not adding to UPDATE statement (C#, MVC)

If you look at the stuff commented out, I can easily get this to work by adding user input directly in to the query, but when I try to parameterize it, none of the values are being added to the parameters...
This code is throwing an error
Must define table variable #formTable
but the issue is none of the values are adding, not just the table variable (verified by replacing table name variable with static text).
I have many insert statements in this project structured exactly like this one which work perfectly. What am I doing wrong here?
string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
//string query = "UPDATE " + s.formTable + " SET " + s.column + " = '" + s.cellValue + "' WHERE MasterID = '" + s.id + "'";
string query = "UPDATE #formTable SET #column = #cellValue WHERE MasterID = #id;";
using (SqlCommand cmd = new SqlCommand(query))
{
//SqlParameter param = new SqlParameter("#formTable", s.formTable);
//cmd.Parameters.Add(param);
cmd.Parameters.AddWithValue("#formTable", s.formTable);
cmd.Parameters.AddWithValue("#column", s.column);
cmd.Parameters.AddWithValue("#cellValue", s.cellValue.ToString());
cmd.Parameters.AddWithValue("#id", s.id.ToString());
cmd.Connection = con;
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
}
Parameters are for values, not object identifiers (tables, columns, etc.), so the only valid parameters you have are #cellValue and #id.
If you want to dynamically set table/column names based on user input, you're likely looking at string concatenation. However, that doesn't necessarily mean SQL injection. All you need to do is validate the user input against a set of known values and use the known value in the concatenation.
For example, suppose you have a List<string> with all of your table names. It can be hard-coded if your tables are never going to change, or you can make it more dynamic by querying some system/schema tables in the database to populate it.
When a user inputs a value for a table name, check if it's in the list. If it is, use that matching value from the list. If it isn't, handle the error condition (such as showing a message to the user). So, even though you're using string concatenation, no actual user input is ever entered into the string. You're just concatenating known good values which is no different than the string literals you have now.

Use an Access Forms Unbound text box as a Field filter in a table

Access 2013 - Reference an Unbound text box on a Form
I am currently trying to use an unbound text box [Text161] on a Form name [DCM_Gap_Servers] to sort information through a table. I want the query that I created to be able to take the users input from [DCM_Gap_Servers]![Text161] as the field that is being sorted from the table names 'Server'.
This is the SQL I am using right now in the query:
SELECT * FROM Servers WHERE "Forms![DCM_Gap_Servers]![Text161]" IS NULL
** I have already Tried:
"Forms![DCM_Gap_Servers]![Text161]" ; (Forms![DCM_Gap_Servers]![Text161]); Forms.[DCM_Gap_Servers]![Text161]
This will work at any time if I replace the Text Box reference with the actual Field name I am using, but since there are hundreds of combinations of fields, I need the reference to work.
I have looked all over, and I can't seem to find the correct answer. I am willing to do it in VBA if needed, whatever it takes to get the filtering done correctly.
Thank You.
It is:
SELECT * FROM Servers WHERE Forms.[DCM_Gap_Servers].[Text161] IS NULL
but that will just select all records whenever your textbox is Null.
So it rather is:
SELECT * FROM Servers WHERE SomeField = Forms.[DCM_Gap_Servers].[Text161]
To use the form value as a field name, you must use concatenated SQL:
strSQL = "SELECT * FROM Servers WHERE " & Forms![DCM_Gap_Servers]![Text161].Value & " IS NULL"
This you might pass to the SQL property of an existing query object:
MyQueryDef.SQL = strSQL
Or:
Constant SQL As String = "SELECT * FROM Servers WHERE {0} IS NULL"
FieldName = Forms![DCM_Gap_Servers]![Text161].Value
MyQueryDef.SQL = Replace(strSQL, "{0}", FieldName)
Of course, take care the the field name isn't a zero length string.

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...

Using a VBA array in a SQL statement

I am trying to write some code that uses SQL to delete rows from several tables.
A user would type type numbers into a textbox that are separated by a comma which is used in the WHERE clause of a SQL DELETE statement.
I have managed to split the string into a variant array and now I want to insert it into my SQL statement.
How do I insert the variable into the SQL statement and have it run through every element of the array?
EDIT: A bit more digging has taught me about For Each Next statements. This is probably what im looking for.
I suggest you build your query in VBA, then your list of numbers can be an IN statement:
sSQL = "DELETE FROM table WHERE ID In (" & MyList & ")"
Where MyList = "1,2,3,4" or such like.
As you can see, you do not need an array and a textbox would be more suitable than a combobox. If you wish to allow your users to select by say, a name, then a listbox is useful. You can iterate through the selected items in the listbox and build a string from IDs to be used in the Delete statement. ( MS Access 2007 - Cycling through values in a list box to grab id's for a SQL statement )
You can then execute the sql against an instance of a database. For example:
Dim db As Database
Set db = CurrentDB
db.Execute sSQL, dbFailOnError
MsgBox "You deleted " & db.RecordsAffected & " records."
A generic approach
WHERE
','+Array+',' like '%,'+col+',%'
It will consider all the numbers available in your Array
You could make it simple and elaborate a string, something like
stringBuilder sb = StringBuilder("DELETE FROM YOURTABLE WHERE ");
foreach(string st in stringArray){
sb.append("YOURFIELD='" + st + "'");
//If it is not the last element, add an "OR"
if (st != stringArray[stringArray.length -1]) sb.append(" OR ");
}
//Now, you have a string like
//DELETE FROM YOURTABLE WHERE YOURFIELD='hello' OR YOURFIELD='YES'
//... do something with the command
This method will fail if you want to run SQL query on two (or multiple) columns using array values from two different arrays. .e.g
where col1=array1(i) and col2=array2(i)