SELECT Syntax error in query. Incomplete query clause - sql

I am trying to make the same sql SELECT for every row.
But, I get a problem in the 'showReader = sqlShowSol.ExecuteReader();'
It says - "Syntax error in query. Incomplete query clause."
Why is it?
-- connection was established before. --
System.Data.OleDb.OleDbCommand sqlShowSol = new System.Data.OleDb.OleDbCommand();
sqlShowSol.Connection = connection;
System.Data.OleDb.OleDbDataReader showReader;
int row = 1;
while (true)
{
sqlShowSol.CommandText = "SELECT Q_A,Content FROM #userName WHERE id = #id;";
sqlShowSol.Parameters.AddWithValue("#userName", userName);
sqlShowSol.Parameters.AddWithValue("#id", row);
showReader = sqlShowSol.ExecuteReader();
|-----------------------------------------------------------------------------------------|
There is more code afterwords...
But I get the problem in the last line I typed here.
Tnx 4 help,
Etay

When you write this:
"SELECT Q_A,Content FROM #userName WHERE id = #id;";
You are using a paramater incorrectly. You are not permitted to use a parameter as the table name. The database engine cannot interpret the #userName reference.

Related

java.sql.SQLSyntaxErrorException: ORA-00933: SQL command not properly ended with WHERE clause

I am trying to execute a query in my Oracle database with a WHERE clause:
java.sql.Date today = new java.sql.Date(System.currentTimeMillis());
String sql = new StringBuilder("SELECT *")
.append("FROM USERNAME.MY_TABLE m")
.append("WHERE m.A_DATE_COLUMN = ?").toString();
PreparedStatement ps = con.prepareStatement(sql);
ps.setDate(1, today);
ResultSet rs = ps.executeQuery();
But I keep getting error:
SQL command not properly ended
when executeQuery() is called. I know it has to do with setting my parameters because the query runs fine and returns the proper data if I don't include the WHERE clause. The table I am querying from has just the one column which is of type DATE.
I tried using setString instead of setDate and adding a semicolon after ? inside my String I use to create my query, but it's my understanding I don't want to include a semicolon.
You need to add spaces:
String sql = new StringBuilder("SELECT * ")
.append("FROM USERNAME.MY_TABLE m ")
.append("WHERE m.A_DATE_COLUMN = ? ").toString();
After the append, your query looks like below.
SELECT *FROM USERNAME.MY_TABLE mWHERE m.A_DATE_COLUMN = ?
Add the spaces properly.
String sql = new StringBuilder("SELECT * ")
.append("FROM USERNAME.MY_TABLE m ")
.append("WHERE m.A_DATE_COLUMN = ?").toString();

Empty result on native SQL query on Hibernate

I am trying to develop a simple method to execute sql queries on my application so I can use native sql for certain things.
This is the method I have:
Session session = getReportCsvMgr().getHibernateSession();
session.beginTransaction();
String sql = String.format("select USER_ID from Users where accountid = 'testaaa'");
Object o = session.createSQLQuery(sql).list();
System.out.println(o.toString());
session.close();
I do not get any errors but somehow the object o is empty and the sysout just prints [].
I debugged and the session works. I tested changing the name of the table and indeed it said "table does not exist". I also tried with and update statement, no errors but it does nothing.
Can anybody tell me what I need to do?
Thanks!
Change the line
Object o = session.createSQLQuery(sql).list();
to:
List<Integer> o = session.createSQLQuery(sql).list();
it the USER_ID is integer or to:
List<String> o = session.createSQLQuery(sql).list();
if the USER_ID is string.
Moreover in a query you have not passed params so you can change:
String sql = String.format("select USER_ID from Users where accountid = 'testaaa'");
to simple:
String sql = "select USER_ID from Users where accountid = 'testaaa'";
Either use .uniqueResult() instead of .list() if it only returns one row or change the return type to List<Object[]>

sql statement single quote double quote - Either BOF or EOF is true

Can you please help me with my sql statement? both studentID and password are text.
I thought I figured out the single quote and double quote but apparently not as i am getting the error " Either BOF or EOF is True, or the current record has been deleted. Requested operation requires a current record ".
There is records in my table members.
var mycon;
mycon = new ActiveXObject("ADODB.Connection");
var myrec ;
myrec= new ActiveXObject("ADODB.Recordset");
mycon.Open("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Database2.mdb");
var txtpassword = Request.QueryString("txtpassword");
var txtuserID = parseInt (Request.QueryString("txtuserID"));
var sql;
sql = "SELECT * FROM Members WHERE StudentID='"+txtuserID+"'AND Password='"+txtpassword+"'";
myrec.Open (sql, mycon);
Your syntax looks incorrect as you do not have a space between the txtuserID value and your and in your sql var. It should look like this
"SELECT * FROM Members WHERE StudentID = '"+txtuserID+"' AND Password
='"+txtpassword+"'";
txtuserID = parseInt (Request.QueryString("txtuserID"));
You are parsing the txtuserID to an INT.
You should not put it in quotes, so you could change your SQL to:
"SELECT * FROM Members WHERE StudentID= "+txtuserID+" AND Password='"+txtpassword+"'";
Correct me if I'm wrong, but in:
var sql;
sql = "SELECT * FROM Members WHERE StudentID='"+txtuserID+"'AND Password='"+txtpassword+"'";
The SQL statement in the text isn't finished with a ";".

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.

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