This is a native create statement for some unknown database carrier
String createStatement = "CREATE TABLE test_database.test_table " +
"AS " +
"( " +
"var1, " +
"var2 " +
") " +
"; "
);
I need to parse this String test_database.test_table
I don't know in advance what SQL flavor this CREATE statement is. If I knew that, I would simply use something like
String table = createStatement.split(" ")[2];
But the above solution might not work in all databases. What if some database allows for blanks in table name? So I have to use Hibernate.
How?
In general, I don't think you can do this without certain assumptions or considering each and every SQL dialect you want to support.
Hibernate itself supportes a number of SQL dialects and you can infer a lot of things from the used dialect. However, org.hibernate.dialect.Dialect does not provide enough information for parse all the possible native CREATE TABLE statements in the selected dialect.
I don't think that Hibernate can take care of all situations especially when dealing with something like Transact-SQL or CREATE GLOBAL TEMPORARY TABLE or even CREATE TEMPORARY TABLESPACE and then you have the AS, AS SELECT, and even PARALLEL COMPRESS AS SELECT after the table name to consider.
As an alternative however you can create a method which can retrieve the Table Name from a supplied CREATE TABLE SQL string which I believe will cover most (if not all) of these issues. Below is such a method:
public String getTableNameFromCreate(final String sqlString) {
// Always rememeber...we're only trying to get the table
// name from the SQL String. We really don't care anything
// about the rest of the SQL string.
String tableName;
String wrkStrg = sqlString.replace("[", "").replace("]", "").trim();
// Is "CREATE TABLE" only
if (wrkStrg.startsWith("CREATE TABLE ")) {
wrkStrg = wrkStrg .substring(13).trim();
}
else if (wrkStrg.startsWith("CREATE GLOBAL TEMPORARY TABLE ")) {
wrkStrg = wrkStrg .substring(30).trim();
}
else if (wrkStrg.startsWith("CREATE TEMPORARY TABLESPACE ")) {
wrkStrg = wrkStrg .substring(28).trim();
}
// Is it Create Table ... AS, AS SELECT, PARALLEL COMPRESS AS,
// or PARALLEL COMPRESS AS SELECT?
if (wrkStrg.toUpperCase().contains(" PARALLEL COMPRESS ")) {
wrkStrg = wrkStrg.replace(" parallel compress ", " PARALLEL COMPRESS ");
tableName = wrkStrg.substring(0, wrkStrg.indexOf(" PARALLEL COMPRESS ")).trim();
}
else if (wrkStrg.toUpperCase().contains(" AS ")) {
wrkStrg = wrkStrg.replace(" as ", " AS ");
tableName = wrkStrg.substring(0, wrkStrg.indexOf(" AS ")).trim();
}
// Nope...none of that in the SQL String.
else {
tableName = wrkStrg.substring(0, wrkStrg.indexOf("(")).trim();
}
// return but remove quotes first if any...
return tableName.replace("\"","").replace("'", "");
}
If the database name is attached to the table name as in your example (test_database.test_table) then of course you will need to further parse off the actual table name.
Related
I have for loop in my program where I save new objects to database. It looks like
for (String value: readvalue.readValue()) {
Value value= getValueForSomething(something);
System.out.println(value);
valueRepository.save(value);
}
And this fragment of code is executed every 30s and saving to database all values. Some values in database have two same fields and one other. How can I update values in h2 database instead of insert new?
I would suggest that within your for loop, create a method that checks to see if the object already exists in your H2 DB by querying for it using an unique identifier like an id. Use the following example RDB query as a reference:
private static final String PRODUCT_ALREADY_EXISTS_QUERY = "SELECT EXISTS(SELECT 1"
+ " FROM inventory.products "
+ " WHERE 1 = 1"
+ " AND id = :id)";
Then, if the record does exists, then call an update method that utilizes a query to UPDATE using the unique identifier. An RDB example query would be:
private static final String UPDATE_QUERY = "UPDATE inventory.products"
+ " SET (company_id, name, price, type, quantity, created_date, last_modified_date) = "
+ " (:companyId, :productName, :price, :productType, :quantity, :createdDate, :lastModifiedDateTime)"
+ " WHERE id = :id ";
If the record doesn't exist, then just create the record like you are.
I am having code something like this.
final PreparedStatement stmt = connection
.prepareStatement("delete from " + fullTableName
+ " where name= ?");
stmt.setString(1, addressName);
Calculation of fullTableName is something like:
public String getFullTableName(final String table) {
if (this.schemaDB != null) {
return this.schemaDB + "." + table;
}
return table;
}
Here schemaDB is the name of the environment(which can be changed over time) and table is the table name(which will be fixed).
Value for schemaDB is coming from an XML file which makes the query vulnerable to SQL injection.
Query: I am not sure how the table name can be used as a prepared statement(like the name used in this example), which is the 100% security measure against SQL injection.
Could anyone please suggest me, what could be the possible approach to deal with this?
Note: We can be migrated to DB2 in future so the solution should compatible with both Oracle and DB2(and if possible database independent).
JDBC, sort of unfortunately, does not allow you to make the table name a bound variable inside statements. (It has its reasons for this).
So you can not write, or achieve this kind of functionnality :
connection.prepareStatement("SELECT * FROM ? where id=?", "TUSERS", 123);
And have TUSER be bound to the table name of the statement.
Therefore, your only safe way forward is to validate the user input. The safest way, though, is not to validate it and allow user-input go through the DB, because from a security point of view, you can always count on a user being smarter than your validation.
Never trust a dynamic, user generated String, concatenated inside your statement.
So what is a safe validation pattern ?
Pattern 1 : prebuild safe queries
1) Create all your valid statements once and for all, in code.
Map<String, String> statementByTableName = new HashMap<>();
statementByTableName.put("table_1", "DELETE FROM table_1 where name= ?");
statementByTableName.put("table_2", "DELETE FROM table_2 where name= ?");
If need be, this creation itself can be made dynamic, with a select * from ALL_TABLES; statement. ALL_TABLES will return all the tables your SQL user has access to, and you can also get the table name, and schema name from this.
2) Select the statement inside the map
String unsafeUserContent = ...
String safeStatement = statementByTableName.get(usafeUserContent);
conn.prepareStatement(safeStatement, name);
See how the unsafeUserContent variable never reaches the DB.
3) Make some kind of policy, or unit test, that checks that all you statementByTableName are valid against your schemas for future evolutions of it, and that no table is missing.
Pattern 2 : double check
You can 1) validate that the user input is indeed a table name, using an injection free query (I'm typing pseudo sql code here, you'd have to adapt it to make it work cause I have no Oracle instance to actually check it works) :
select * FROM
(select schema_name || '.' || table_name as fullName FROM all_tables)
WHERE fullName = ?
And bind your fullName as a prepared statement variable here. If you have a result, then it is a valid table name. Then you can use this result to build a safe query.
Pattern 3
It's sort of a mix between 1 and 2.
You create a table that is named, e.g., "TABLES_ALLOWED_FOR_DELETION", and you statically populate it with all tables that are fit for deletion.
Then you make your validation step be
conn.prepareStatement(SELECT safe_table_name FROM TABLES_ALLOWED_FOR_DELETION WHERE table_name = ?", unsafeDynamicString);
If this has a result, then you execute the safe_table_name. For extra safety, this table should not be writable by the standard application user.
I somehow feel the first pattern is better.
You can avoid attack by checking your table name using regular expression:
if (fullTableName.matches("[_a-zA-Z0-9\\.]+")) {
final PreparedStatement stmt = connection
.prepareStatement("delete from " + fullTableName
+ " where name= ?");
stmt.setString(1, addressName);
}
It's impossible to inject SQL using such a restricted set of characters.
Also, we can escape any quotes from table name, and safely add it to our query:
fullTableName = StringEscapeUtils.escapeSql(fullTableName);
final PreparedStatement stmt = connection
.prepareStatement("delete from " + fullTableName
+ " where name= ?");
stmt.setString(1, addressName);
StringEscapeUtils comes with Apache's commons-lang library.
I think that the best approach is to create a set of possible table names and check for existance in this set before creating query.
Set<String> validTables=.... // prepare this set yourself
if(validTables.contains(fullTableName))
{
final PreparedStatement stmt = connection
.prepareStatement("delete from " + fullTableName
+ " where name= ?");
//and so on
}else{
// ooooh you nasty haker!
}
create table MYTAB(n number);
insert into MYTAB values(10);
commit;
select * from mytab;
N
10
create table TABS2DEL(tname varchar2(32));
insert into TABS2DEL values('MYTAB');
commit;
select * from TABS2DEL;
TNAME
MYTAB
create or replace procedure deltab(v in varchar2)
is
LvSQL varchar2(32767);
LvChk number;
begin
LvChk := 0;
begin
select count(1)
into LvChk
from TABS2DEL
where tname = v;
if LvChk = 0 then
raise_application_error(-20001, 'Input table name '||v||' is not a valid table name');
end if;
exception when others
then raise;
end;
LvSQL := 'delete from '||v||' where n = 10';
execute immediate LvSQL;
commit;
end deltab;
begin
deltab('MYTAB');
end;
select * from mytab;
no rows found
begin
deltab('InvalidTableName');
end;
ORA-20001: Input table name InvalidTableName is not a valid table name ORA-06512: at "SQL_PHOYNSAMOMWLFRCCFWUMTBQWC.DELTAB", line 21
ORA-06512: at "SQL_PHOYNSAMOMWLFRCCFWUMTBQWC.DELTAB", line 16
ORA-06512: at line 2
ORA-06512: at "SYS.DBMS_SQL", line 1721
I am new to using SQL2O with MySQL, but I am having a weird problem, where different queries return same results. Is SQL2O returning me cached results?
My code looks like this:
String sql = "SELECT * " +
"FROM report_A" +
"ORDER BY :order :sequence "+
"LIMIT :from, :limit";
int limit = 5;
int startIndex = (page-1)*limit;
String sequence = "DESC";
try(Connection con = sql2o.open()) {
if(order.contains("-")){
order = order.replace("-", "");
sequence= " ASC";
}
Query query= con.createQuery(sql)
.addParameter("from", startIndex)
.addParameter("limit", limit)
.addParameter("order", order)
.addParameter("sequence", sequence);
List<ReportA> result = query.executeAndFetch(ReportA.class);
con.close();
The 4 parameters always change, but the output remains the same. I have verified the queries in mysql workbench, the data is different, but SQL2O returns me the same set of data. Am I missing something?
Your query is invalid. It wont compile and throw an Sql2oException on execution.
The problem is, basically, that you can use parameters only for values, not for table names, column names or other keywords like "ASC". Changing those would change the structure of the query.
It's possible to construct queries with variable structure by good old string concatenation, i.e.
String sql = "SELECT * " +
"FROM report_A" +
"ORDER BY " + order " " + SEQUENCE +
"LIMIT :from, :limit";
and then
query(sql)
.addParameter("from", from)
.addParameter("limit", limit)
.executeAndFetch(...)
So, i would like to retrieve database information where a user will search certain columns using text fields, like this:
column1 find userinput,
column2 find userinput,
column3 find userinput,
The problem im having is the sql statement:
String sql = "select * from table where column = '" + textfield1.getText() + "'";
If textfield1 is empty, it will only retrieve entries that contain nothing.
What im trying to retrieve will have 6 text field, meaning 6 columns in the database. Using java i would need alot of if statements.
Is there any other way to shorten this?
EDIT
-- MORE INFO --
The if statements will start from:
if (!(t1.getText().equals("")) && !(t2.getText().equals("")) && !(t3.getText().equals(""))
&& !(t4.getText().equals("")) && !(t5.getText().equals("")) && (t6.getText().equals("")))
all the way down to
if (t1.getText().equals("") && t2.getText().equals("") && t3.getText().equals("")
&& t4.getText().equals("") && t5.getText().equals("") && t6.getText().equals("")
covering all possible combinations of the 6 input fields, the point of all these statements is to ignore empty text fields but provide the corresponding sql statement.
I don't know how to calculate the possible combinations other than writing them all down(i started, there was too many).
I didn't really understand why those ifs, you should elaborate more your question but i will try to help as i can.
Well, if you want to retrieve everything from the database you could use LIKE:
String sql = "select * from table where column like '%" + textfield1.getText() + "%'";
This way you'll get everything with the containing text, it means, if the field is empty it will bring all results, i guess this is the best way to do, to avoid unnecessa if clauses.
Another thing, to check for empty fields you should use:
t1.getText().trim().isEmpty()
BUT if you let they write white spaces the LIKE won't help you then you need to .trim() all your texts then your white spaces will be ignored.
The following can be formulated much neater, but to make the point:
JTextField ts = new JTextField[6];
Set<String> values = new HashSet<>(); // Removes duplicates too.
for (JTextField t : ts) {
String text = ts.getText().trim();
if (!text.isEmpty()) {
values.add(text);
}
}
// Build the WHERE condition of a PreparedStatement
String condition = "";
for (String value : values) {
condition += condition.isEmpty() ? "WHERE" : " OR";
condition += " column = ?";
}
String sql = "select * from table " + condition;
PreparedStatement stm = connection.prepareStatement(sql);
int index = 1; // SQL counts from 1
for (String value : values) {
stm.setString(index, value);
++index;
}
ResultSet rs = stm.executeQuery();
The usage of a PreparedStatement makes escaping ' (and backslash and such) no longer needed and also prevents SQL injection (see wikipedia).
i have a problem i want to search data based on multiple jtext fields where did i go wrong coz this displays only one row which has the first id
private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {
// TODO add your handling code here:
String sql="SELECT Employee.EmpID,Employee.Fname,Employee.Mname,Employee.Sname,Employee.DoB,Employee.Phone,"
+ "Employee.Email,Employee.Nationality,Employee.Desegnition,Employee.NSSF,Employee.WCF,"
+ "Employee.BSalary,Allowance.medical,Allowance.Bonus,Allowance.others,Allowance.tov,Allowance.TA,"
+ "Attendece.Hrs from Employee,Allowance,Attendece WHERE "
+ "Employee.EmpID=Allowance.EmpID and Attendece.EmpID=Allowance.EmpID AND Employee.EmpID=? AND Attendece.Dt=?";
try{
pd=conn.prepareStatement(sql);
pd.setString(1,id.getText());
pd.setString(2,Date1.getText());
r=pd.executeQuery();
//setting the text fields
if(r.next())
{
String a=r.getString("EmpID");
eid.setText(a);
String b=r.getString("Fname");
fname.setText(b);
String c=r.getString("Mname");
mname.setText(c);
String d=r.getString("Sname");
sname.setText(d);
String e=r.getString("DoB");
dob.setText(e);
String f=r.getString("Desegnition");
Des.setText(f);
String g=r.getString("Bsalary");
bsal.setText(g);
String h=r.getString("Phone");
phone.setText(h);
String i=r.getString("Email");
email.setText(i);
String j=r.getString("Nationality");
nationality.setText(j);
String k=r.getString("Desegnition");
Des.setText(k);
String l=r.getString("NSSf");
nssf.setText(l);
String m=r.getString("WCF");
wcf.setText(m);
String n=r.getString("tov");
oh.setText(n);
String o=r.getString("Bonus");
bn.setText(o);
String p=r.getString("medical");
md.setText(p);
String q=r.getString("others");
ot.setText(q);
String s=r.getString("TA");
ta.setText(s);
String t=r.getString("Hrs");
hrs.setText(t);
int day;
day=Integer.parseInt(t)/8;
days.setText(Integer.toString(day));
double week=day/7;
weeks.setText(Double.toString(week));
}
r.close();
pd.close();
}catch(Exception e)
{
}
I am using an sql query to add data data to an existing database table.
I want to add data under the columns 'Room_Resource' and 'Quantity'.
The system is designed to allow bookings and i am trying to add bookings made to a tblBookings table, the code below is taken from JButton clicked function.
The value I want to add to Room_Resource is a name taken from a selected table within the system. I declared a variable for this 'resourceChosenString'
The value I want to add to quantity is from the 'Quantity' variable i have declared in relation to a combo box.
Here are my declarations:
int selectedResourceRow = tblResources.getSelectedRow();
Object resourceChosen = tblResources.getValueAt(selectedResourceRow,1);
String resourceChosenString = resourceChosen.toString();
int Quantity = cmbQuantity.getSelectedIndex();
I then have a sql statement:
String sql = ("INSERT INTO tblBookings (Room_Resource,Quantity) VALUES (" + resourceChosenString + " ', ' " + Quantity + " ',) ");
And then the execute code:
try{
pst = conn.prepareStatement(sql);
pst.execute();
JOptionPane.showMessageDialog(null, "Added");
} catch (Exception e){
JOptionPane.showMessageDialog(null, "Error Adding Booking");
}
Currently it gives me an error when I attempt to add the data to the table and wondered if anyone had any suggestions?
Also I considered that perhaps the problem could lie in the fact I have more than two columns in the external table and the table I am adding the data to so columns could be left blank. If this could be the problem, could anyone tell me how to get around it? Possibly if there is a null function I can use instead of values.
You probably want to tell us what database you're using and what error message you're getting. But just off the bat, it looks like your sql string is not formatted correctly. I don't know if you mistyped it in the question or if your code has a simple syntax error.
Just shooting from the hip with what you have, it looks like your sql statement should be:
String sql = "INSERT INTO tblBookings (Room_Resource,Quantity) VALUES ('" + resourceChosenString + "', " + Quantity + ")";
Notice that resourceChosenString should be wrapped in single quotes (you're missing the single quote on the left). Also, I don't think you're supposed to wrap a number in single quotes (I could be wrong since I don't know which database you're using).
Qwerky is right though; you should use a PreparedStatement.
The SQL you are generating is not valid and looks like this;
INSERT INTO tblBookings (Room_Resource,Quantity) VALUES (resource ', ' 1 ',)
^ ^
missing quote extraneous comma
You should tidy it up, or better still use a PreparedStatement.
String sql = "insert into tblBookings (Room_Resource,Quantity) values (?, ?)";
PreparedStatement pst = conn.prepareStatement(sql);
pst.setString(1, resourceChosenString);
pst.setInt(2, quantity); //variable names are not capitalised by convention
pst.execute();