I am using Eclipse and Oracle SQL Developer. My connections are all set up. I am trying to query my database in SQL Developer by passing in a column name as a variable.
For example, I just want to use something similar to this statement:
select * from CUSTOMERS;
but allow CUSTOMERS to be a variable where I can pass in any table name.
Currently this pulls all column names from given column name and connection:
final String query = "select column_name from all_tab_columns"
+" where owner = ?"
+" and table_name = ?";
try {
headers = DAO.useJNDI(jndi)
.setSQL(query)
.input(1, host)
.input(2, tableName)
.list(String.class);
I want to do the same thing but with rows. Does anyone know how to do this? This is what I am thinking about so far:
final String sql = "select *"
+ " from table_name"
+ " where owner = ? and table_name = ?";
try {
logger.debug(tableName+sourceJNDI);
sourceList = DAO.useJNDI(sourceJNDI)
.setSQL(sql)
.input(1, host)
.input(2, tableName)
.list(DatabaseCompareDto.class);
The main focus is the SQL statements. I know everything else works.
If I'm reading your question correctly, I think what you want is to replace the first table_name in your SQL with ?, then add an additional .input( 1, tableName) :
final String sql = "select *"
+ " from ?"
+ " where owner = ? and table_name = ?";
try {
logger.debug(tableName+sourceJNDI);
sourceList = DAO.useJNDI(sourceJNDI)
.setSQL(sql)
.input(1, tableName)
.input(2, host)
.input(3, tableName)
.list(DatabaseCompareDto.class);
You can't pass the table name as a parameter. Instead of wasting your energy on such an alleged generic solution, use or create a small templating engine which allows you to replace the table name in your query before sending it to the database.
Related
I have a question about SQLite in GDScript.
I wanted to print one query result to debug but I cannot find the way to do it.
In my code I have:
var tableName = "users"
db.query("SELECT username, email FROM " + tableName + " WHERE username=?;" + (username))
I cannot pass the username as "username", what is the correct way to do it?
I also try this:
var tableName = "users"
db.query("SELECT username, email FROM " + tableName + " WHERE username= " + username + ";")
And this:
var tableName = "users"
db.query("SELECT username, email FROM " + tableName + " WHERE username = " + 'username' + ";")
By the way, im getting the username from this:
var username = $NinePatchRect/VBoxContainer/username.get_text()
I've printed and the variable username is fine.
Thank you all!
What to do
The proper way to do this, is with prepared statements and argument bindings. You need to find a way to do that with whatever solution you are using.
If you are using this solution: 2shady4u/godot-sqlite (Which is available from the Godot Asset Library, here). Do the following:
var query = "SELECT username, email FROM " + tableName + " WHERE username=?;"
db.query_with_bindings(query, [username])
Which should use prepared statements and argument bindings behind the scenes. Source.
If you are using this solution: godot-extended-libraries/godot-sqlite (towards which the Godot Core developers contributed). Do the following:
var query = "SELECT username, email FROM " + tableName + " WHERE username=?;"
db.query_with_args(query, [username])
Which should use prepared statements and argument bindings behind the scenes. Source.
If you are using this solution: khairul169/gdsqlite-native (which is an older project). Do the following:
var query = "SELECT username, email FROM " + tableName + " WHERE username=?;"
db.query_with_args(query, PoolStringArray([username]))
Which should use prepared statements and argument bindings behind the scenes. Source.
If you are using another solution, please figure out how to use prepared statements with it. And if there is no way to do it, please switch to a solution that supports them, such as the ones linked above.
What NOT to do, and why
SQLite needs the strings between quotation marks.
A common way to put quotation marks in Godot is by writing your string between ' instead of ".
For example:
print('Hello "World"')
Should print Hello "World".
Alternatively, you can use escape sequences:
print("Hello \"World\"")
Which should also print Hello "World".
Thus, you can - please don't - make your query like this:
db.query("SELECT username, email FROM " + tableName + " WHERE username= \"" + username + "\";")
Then if the user typed:
peter
The query would be built like this (And let us say tableName is users):
SELECT username, email FROM users WHERE username= "peter";
And you would have a SQL injection vulnerability. If the user writes a quotation mark, then the rest of the string will be considered part of the query.
For example if the user writes
" or "" = "
The query will be built like this:
SELECT username, email FROM users WHERE username= "" or "" = "";
And that will return all users. And that is just an example of what they could write, because remember they would be writing SQL.
Prepared statements avoids the vulnerability. And not by string tricks, but by proper support. And without the hassle. Please use prepared statements.
The code is suppose to check my database to see if there are duplicates of activityName existing if that query runs I am suppose to get an error stating that the activity name is taken else if there isn't any activity name in that database with the same name then the activity name would be inserted into the database. Im suppose to execute the query and get the result as an Integer then use the result in the if and else to see if result>0 in the database
var queryCount= 'SELECT COUNT (activityName) FROM dataEntryTb WHERE activityName = "'+an+'" ';
tx.executeSql(queryCount,[]);
if(queryCount > 0){
navigator.notification.alert("Activity Name Taken");
}else{
Not sure what's the issue exactly but it should work fine. You can consider changing it like
var queryCount= "SELECT 1 FROM dataEntryTb WHERE activityName = '" + an + "'";
Again, consider using parameterized query instead of string concatenation to avoid SQL Injection (if an is coming as user input)
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("'", "''"))
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.
String sql = "select * from file_repo_index where id in (?)";
PreparedStatement ps = conn.prepareStatement(sql);
ps.setString (1, toCommaSeparatedList(repoIdList));
ResultSet result = ps.executeQuery();
public static String toCommaSeparatedList(Collection col);
I have to use the query as
select * from file_repo_index where id in ( 1,2,3,4 )
But it gives following error in executeQuery() statement
java.sql.SQLException: Conversion failed when converting the nvarchar value '213304,213305,213307' to data type int.
I can use it like
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Statement ps = conn.createStatement();
ResultSet result = ps.executeQuery(sql);
But I want to use the PrepareStatment method. How can I do it. ??
You should create your prepare statement placeholders based on your values, for instance:
String sql = "select * from file_repo_index where id in (";
//append ?, in above sql in a loop
//Then prepare statement.
This will involve a bit of extra coding, but i think this is the only way to force using PreparedStatement.
If You want to use IN keyword then inside the brackets you have to put like
('213304','213305','213307')
as seperate variables and dont combine in a single "single quotes the entire values" and also in the select statement
String sql = "select * from file_repo_index where id in ("+toCommaSeparatedList(repoIdList)+")";
Change the double quotes to single and try
('+ toCommaSeparatedList(repoIdList) +')";