Can't retrieve data from the database - sql

I'm a little in need of your help
In my web application I have this Select statement, but once I run it, it retrieves 0 data but when I try my Select statement in the database it has data in it, and my Select statement is correct, by the way my application is already published in the server.
Here's my code
string SelectStatement = "SELECT DATEDIFF(day, kg1653, GETDATE()) datenum, kg1635, (CASE WHEN kg1637 is null THEN 0 END) eis ";
string FromStatement = "FROM hsi.keygroupdata503 ";
string WhereStatement = "WHERE kg1235='" + _securityCode + "' and kg1241 is null";
_sqlDT = ConnectToDatabase(SelectStatement + FromStatement + WhereStatement);
and here's my connection string
System.Data.Odbc.OdbcConnection _odbcConn = new System.Data.Odbc.OdbcConnection();
_odbcConn.ConnectionString = "MY DATABASE CONNECTION STRING";
System.Data.Odbc.OdbcDataAdapter _odbcA = new System.Data.Odbc.OdbcDataAdapter(sqlQuery1, _odbcConn);
DataTable _odbcDt = new DataTable();
_odbcA.Fill(_odbcDt);
return _odbcDt;
Can somebody please help me with this?
Thank you so much!

When does sqlQuery1 get set to _sqlDT ... your best bet is to debug and see what the query is right on the line of it being called and copy it to run on the SQL server in case something else is updating it or _scurityCode is empty. Also if you have a test environment with similar table names, make sure you are connecting to the same live instance.
Side note, not foolproof but make sure _securityCode has a replace statement and change all single quotes to double quotes to work against SQL injection as the commentor above said.

Related

SQL Server : drop table with SQL parameters

I'm trying to drop a table using SqlParameters. I have this code .
dbCon.Open();
DataRowView d= (DataRowView) cmbTabele.Items[cmbTabele.SelectedIndex];
string name = (d["table_name"]as string);
SqlCommand com=new SqlCommand("drop table #nume ", dbCon);
com.Parameters.Clear();
SqlParameter param = new SqlParameter("#nume", name);
com.Parameters.Add(param);
com.ExecuteNonQuery(); // ERROR HERE
dbCon.Close();
I receive this error :
Incorrect syntax near '#nume'.
But when I do
SqlCommand com = new SqlCommand("drop table " + name, dbCon);
it works, and I really don't understand this error.
You cannot use a parameter for a table name. Although you'll normally get told off around here for building up a query using string concatenation, this is one occasion where you'll need to!
SqlCommand com=new SqlCommand("drop table " + name, dbCon);
I do not recommand it, but if you really want to use SQLParameter, then it is possible this way.
SqlCommand com=new SqlCommand("EXEC('drop table ''' + #nume + '''')", dbCon);
But really, there is no advantage in doing it this way. This work on SQL Server 2005 and newest version of it.

Keyword search to include Uniqueidentifier field

I'm wanting to let a user search rows in a database by specifying a keyword to look for. There are a few fields I would like to look in for this keyword, one of which is a uniqueidentifier. The problem is, if the keyword is not a GUID, I get the following error message:
Conversion failed when converting from a character string to uniqueidentifier
The SQL I'm using to run the search looks something like this:
// do not use
string sql = #"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
WARNING: this is just example code - DO NOT write sql commands like this as it creates a security risk
How do I write my SQL select statement such that it will not fail when keyword is not a GUID?
string sql;
Guid id;
if (Guid.TryParse(keyword, out id))
{
sql = #"SELECT *
FROM [MyTable]
WHERE [MyTable].[TableID] = '" + keyword + "'";
}
else
{
sql = //search by other way
}
Does this work for you?
string sql = #"SELECT *
FROM [MyTable]
WHERE convert(varchar,[MyTable].[TableID]) = '" + keyword + "'";
I know this doesn't really help you today, but may help future readers. In SQL Server 2012 you will be able to use TRY_CONVERT:
string sql = #"SELECT *
FROM dbo.[MyTable]
WHERE [TableID] = TRY_CONVERT(UNIQUEIDENTIFIER, '" + keyword + "');";
But what you really should be doing is passing the parameter as a strongly typed GUID, and handling the error (using try/catch) in the client program when someone enters something that isn't a GUID.

Can my users inject my dynamic sql?

I'm a desktop developer writing for internal users, so I'm not worried about malicious hackers, but I would like to know if there's anything they could enter when updating a value that would execute sql on the server.
The business defines their content schema and I have a CRUD application for them that doesn't have to be changed when their schema changes because the validation details are table-driven and the updates are with dynamic SQL. I have to support single quotes in their data entry, so when they enter them, I double them before the SQL is executed on the server. From what I've read, however, this shouldn't be enough to stop an injection.
So my question is, what text could they enter in a free-form text field that could change something on the server instead of being stored as a literal value?
Basically, I'm building an SQL statement at runtime that follows the pattern:
update table set field = value where pkField = pkVal
with this VB.NET code:
Friend Function updateVal(ByVal newVal As String) As Integer
Dim params As Collection
Dim SQL As String
Dim ret As Integer
SQL = _updateSQL(newVal)
params = New Collection
params.Add(SQLClientAccess.instance.sqlParam("#SQL", DbType.String, 0, SQL))
Try
ret = SQLClientAccess.instance.execSP("usp_execSQL", params)
Catch ex As Exception
Throw New Exception(ex.Message)
End Try
Return ret
End Function
Private Function _updateSQL(ByVal newVal As String) As String
Dim SQL As String
Dim useDelimiter As Boolean = (_formatType = DisplaySet.formatTypes.text)
Dim position As Integer = InStr(newVal, "'")
Do Until position = 0
newVal = Left(newVal, position) + Mid(newVal, position) ' double embedded single quotes '
position = InStr(position + 2, newVal, "'")
Loop
If _formatType = DisplaySet.formatTypes.memo Then
SQL = "declare #ptrval binary(16)"
SQL = SQL & " select #ptrval = textptr(" & _fieldName & ")"
SQL = SQL & " from " & _updateTableName & _PKWhereClauses
SQL = SQL & " updatetext " & _updateTableName & "." & _fieldName & " #ptrval 0 null '" & newVal & "'"
Else
SQL = "Update " & _updateTableName & " set " & _fieldName & " = "
If useDelimiter Then
SQL = SQL & "'"
End If
SQL = SQL & newVal
If useDelimiter Then
SQL = SQL & "'"
End If
SQL = SQL & _PKWhereClauses
End If
Return SQL
End Function
when I update a text field to the value
Redmond'; drop table OrdersTable--
it generates:
Update caseFile set notes = 'Redmond''; drop table OrdersTable--' where guardianshipID = '001168-3'
and updates the value to the literal value they entered.
What else could they enter that would inject SQL?
Again, I'm not worried that someone wants to hack the server at their job, but would like to know how if they could accidentally paste text from somewhere else and break something.
Thanks.
Regardless of how you cleanse the user input increasing the attack surface is the real problem with what you're doing. If you look back at the history of SQL Injection you'll notice that new and even more creative ways to wreak havoc via them have emerged over time. While you may have avoided the known it's always what's lurking just around the corner that makes this type of code difficult to productionize. You'd be better to simply use a different approach.
You can also evaluate an alternative solution. Dynamic generation of SQL with parameters. Something like this:
// snippet just for get the idea
var parameters = new Dictionary<string, object>();
GetParametersFromUI(parameters);
if (parameters.ContainsKey("#id")) {
whereBuilder.Append(" AND id = #id");
cmd.Parameters.AddWithValue("#id", parameters["#id"]);
}
...
Assuming you escape string literals (which from what you said you are doing), you should be safe. The only other thing I can think of is if you use a unicode-based character set to communicate with the database, make sure the strings you send are valid in that encoding.
As ugly as your doubling up code is (:p - Try String.Replace instead.) I'm pretty sure that will do the job.
The only safe assumption is that if you're not using parameterized queries (and you're not, exclusively, here, because you're concatenating the input string into your sql), then you're not safe.
You never never ever never want to build a SQL statement using user input that will be then directly executed. This leads to SQL injection attacks, as you've found. It would be trivial for someone to drop a table in your database, as you've described.
You want to use parameterized queries, where you build an SQL string using placeholders for the values, then pass the values in for those parameters.
Using VB you'd do something like:
'Define our sql query'
Dim sSQL As String = "SELECT FirstName, LastName, Title " & _
"FROM Employees " & _
"WHERE ((EmployeeID > ? AND HireDate > ?) AND Country = ?)"
'Populate Command Object'
Dim oCmd As New OledbCommand(sSQL, oCnn)
'Add up the parameter, associated it with its value'
oCmd.Parameters.Add("EmployeeID", sEmpId)
oCmd.Parameters.Add("HireDate", sHireDate)
oCmd.Parameters.Add("Country", sCountry)
(example taken from here) (also not I'm not a VB programmer so this might not be proper syntax, but it gets the point across)

Sqlcommand Parameters not executing

I am encountering a strange problem when attempting to execute a DELETE query agains a SQL Server table using VB.NET, SQL Command, and Parameters.
I have the following code:
Try
sqlCommand.Transaction = transaction1
sqlCommand.Connection = conn
sqlCommand.CommandText = sqlQuery
sqlCommand.Parameters.Add("#userID", SqlDbType.Int).Value = Convert.ToInt32(userID)
sqlCommand.Parameters.Add("#groupID", SqlDbType.Int).Value = Convert.ToInt32(groupID)
''#Delete the user from the group.
MessageBox.Show("User: " + Convert.ToString(userID) + " Group: " + Convert.ToString(groupID))
MessageBox.Show("Param, UserID: " + sqlCommand.Parameters.Item(0).Value.ToString)
MessageBox.Show("Param, GroupID: " + sqlCommand.Parameters.Item(1).Value.ToString)
return_deleteUser = sqlCommand.ExecuteNonQuery()
Catch ex As Exception
transaction1.Rollback()
Dim hr As Integer = Marshal.GetHRForException(ex)
MsgBox("Removal of user from group has failed: " + ex.Message() & hr)
End Try
Which executes the following SQL Query:
Dim sqlQuery As String = "DELETE FROM MHGROUP.GROUPMEMS WHERE USERNUM =#userID AND GROUPNUM =#groupID"
My problem is that when the code executes, there is no error reported at all. I have ran SQL Profiler and the query doesn't appear in the trace list. The three messageboxes that I have added all return the correct values, and if I was to execute the SQL query against the table with the values the query succeeds. Both the userID and groupID are 3-digit integers.
Can anyone suggest why the code is not working as intended, or any further debugging that I can use to step through the code? Ideally I would love to see the completed SQL query with the parameters completed, but I haven't found out how to do this.
EDIT:
I have the following later in the code to check if the execute's all processed successfully:
If return_insertEvent > 0 And return_updateUser > 0 And return_nextSID > 0 And return_deleteUser > 0 Then
MessageBox.Show("Success")
return_removeADGroup = RemoveUserFromGroup(userID, groupName)
MessageBox.Show("Remove FS User from AD Group: " + return_removeADGroup)
transaction1.Commit()
transaction2.Commit()
transaction3.Commit()
transaction4.Commit()
returnResult = 1
Else
transaction1.Rollback()
transaction2.Rollback()
transaction3.Rollback()
transaction4.Rollback()
returnResult = 0
End If
If you require any further information please don't hesitate in contacting me.
You are missing a Transaction.Commit
Update in respone to additional info added to question:
Why do you have 4 transactions? Since their commit and rollbacks are all executed together, you only need one transaction. I suggest you use a TransactionScope
You can assign the current transaction to ADO.NET Command objects:
ADO.NET and System.Transactions
Transaction Processing in ADO.NET 2.0
I might guess that your calling proc has the values of userid and groupid backwards. If the DELETE doesn't find a matching record, it will complete successfully, but not do anything. I suggest wrapping your delete up in a stored procedure. Then you can add code to test if the parameter values are getting through correctly.
Create Procedure UserDelete
#userid int, #groupID int
As
BEGIN
Select #userid as UID, #groupID as GID INTO TESTTABLE;
DELETE FROM MHGROUP.GROUPMEMS WHERE USERNUM =#userID AND GROUPNUM =#groupID;
END
Run your code then go check the contents of TESTTABLE.
FWIW: I don't like trying to get the whole parameter declaration in one line. Too much going on for me. I like this...
Dim pUID as New Parameter("#userid", SqlDbType.Int)
pUID.Value = userid
cmd.Parameters.Add(pUID)
After some time debugging and sql tracing, I have found out that the stupid application that the DB belongs to treats the group members differently, the groups reside in a administration database, but the users membership to the group resides in another database.
Thank you to everyone above who provided there time and thoughts in assisting with the code. I have changed the code as recomended to use only two transactions and two connections (1 for the admin and sub-database). The code is much nicer now and is that bit easier to read.
Thanks again,
Matt

Syntax error in update statement

code:
string query1 = #"UPDATE global_mapping set escape_id = " +
dataGridView1.Rows[i].Cells[2].Value + ",function_id = " +
dataGridView1.Rows[i].Cells[3].Value + ",function_name = '" +
dataGridView1.Rows[i].Cells[4].Value + "',parameter_name = '" +
dataGridView1.Rows[i].Cells[5].Value + "',parameter_validity = '" +
dataGridView1.Rows[i].Cells[6].Value + "',statusparameter_id = " +
dataGridView1.Rows[i].Cells[7].Value + ",acb_datatype = '" +
dataGridView1.Rows[i].Cells[8].Value + "',data_type_id = " +
dataGridView1.Rows[i].Cells[9].Value + ",bit_size = " +
dataGridView1.Rows[i].Cells[10].Value + ",validity_status ='" +
dataGridView1.Rows[i].Cells[11].Value + "',validity_func = '" +
dataGridView1.Rows[i].Cells[12].Value + "'WHERE global_mapping.parameter_id =" +
dataGridView1.Rows[i].Cells[1].Value + "";
OleDbCommand cmd1 = new OleDbCommand(query1, conn);
cmd1.ExecuteNonQuery();
code ends:
When I execute the above code I get an error stating "Syntax error in Update statement".
Can someone please tell me how to resolve this?
It looks like you need to add a space before your WHERE clause.
Hope this helps,
Bill
Wow. Can we say... SQL Injection?
Try using Parameters. Not only will you protect yourself, but your SQL will become MUCH more readable.
Never use string concatenation for building SQL queries. Use SQL parameters.
Yikes!
Please provide the final query1 value and try to format it so we can get a better picture of it. My guess is a missing ' or something.
I'd say you're missing some quotes in there but your code is such a pig-sty I can't tell. If you won't fix your code then at the minimum give us a dump of query1 so we can read your actual query.
And use parameters or stored procedures like the previous responses said. All it takes is one of your variables to get overwritten with something nasty and your server will be wide open to anyone deleting your tables or worse.
Even if this is a local "safe" database you should unlearn your bad habits now.
Put
Console.WriteLine(query1)
before OleDbCommand cmd1 = new OleDbCommand(query1, conn);
See the value of query1 printed to console window.
Does the SQL Statement look OK? I guess not - you will now be able to find a field which is non-numeric and is blank in the grid.
And, use parameters as others have said.