How to access MySQL field names while reading records - java

I'm using this code to get data from a mysql database:
ResultSet rs= statement.executeQuery(" select id, email from table ");
System.out.println( rs.getInt(1) );
System.out.println( rs.getString(2) );
I want to access field names by their names instead of numerical values as shown above.
Is something like this possible/available:
rs.getValue("id");

I think rs.getInt("id") will work as you'd expect it to.
Also, see ResultSetMetaData.

The method getInt(String columnLabel) in the ResultSet interface will accept a string with the column name, so in your case it will be getInt("id"); and yes it will work.
Cheers.

Related

preparestatement with name [duplicate]

I was wondering if there was any way to specify returned column names using prepared statements.
I am using MySQL and Java.
When I try it:
String columnNames="d,e,f"; //Actually from the user...
String name = "some_table"; //From user...
String query = "SELECT a,b,c,? FROM " + name + " WHERE d=?";//...
stmt = conn.prepareStatement(query);
stmt.setString(1, columnNames);
stmt.setString(2, "x");
I get this type of statement (printing right before execution).
SELECT a,b,c,'d,e,f' FROM some_table WHERE d='x'
I would, however, like to see:
SELECT a,b,c,d,e,f FROM some_table WHERE d='x'
I know that I cannot do this for table names, as discussed
here, but was wondering if there was some way to do it for column names.
If there is not, then I will just have to try and make sure that I sanitize the input so it doesn't lead to SQL injection vulnerabilities.
This indicates a bad DB design. The user shouldn't need to know about the column names. Create a real DB column which holds those "column names" and store the data along it instead.
And any way, no, you cannot set column names as PreparedStatement values. You can only set column values as PreparedStatement values
If you'd like to continue in this direction, you need to sanitize the column names (to avoid SQL Injection) and concatenate/build the SQL string yourself. Quote the separate column names and use String#replace() to escape the same quote inside the column name.
Prepare a whitelist of allowed column names. Use the 'query' to look up in the whitelist to see if the column name is there. If not, reject the query.
For MySQL prepared statements with NodeJS (mysqljs/mysql), what you need to know is that ? is for values, but if you need to escape column names, table names etc, use ?? instead.
Something like this will work:
SELECT ??, ??, ?? FROM ?? WHERE ?? < ?
Set values to ['id', 'name', 'address', 'user', 'id', 100]
I think this case can't work because the whole point of the prepared statement is to prevent the user from putting in unescaped query bits - so you're always going to have the text quoted or escaped.
You'll need to sanitize this input in Java if you want to affect the query structure safely.
Use sql injection disadvantage of Statement Interface as advantage.
Ex:
st=conn.createStatement();
String columnName="name";
rs=st.executeQuery("select "+ columnName+" from ad_org ");
public void MethodName(String strFieldName1, String strFieldName2, String strTableName)
{
//Code to connect with database
String strSQLQuery=String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);
st=conn.createStatement();
rs=st.executeQuery(strSQLQuery);
//rest code
}
Below is the solution in java.
String strSelectString = String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);

How do I uppercase column and table names in a sql statement(Java)?

I have a string that can hold any kind of sql statement(select, update, delete, insert)
I want to uppercase the column and table names in that statement.
Let's say we have:
select id from person where name="Dave"
And I want
select ID from PERSON where NAME="Dave"
Until now I have found some Sql parsers in Java, but I am wondering if there is another faster easier way that parsing the sql and rebuilding it.
EDIT
Just to clarify the question further, the database collation is in Turkish and the problem that I am trying to solve is the "Turkish i problem".
The names of columns/tables in DB are all in uppercase, however the Java application generates sql statements with lowercase columns and tables
You shall use prepared statements with bind variables. By doing that you can uppercase your query and then put bind variables in whatever case you want.
For example:
String query = "select id from person where name=?"
Connection con = .... ;
PreparredStatement ps = con.prepareStatement(query.toUpperCase());
ps.setString(1, "Dave");
ResultSet rs = ps.executeQuery();
Hope this helps.
I'm not sure if I understand your question correctly but if you want to retrieve the specific column name in uppercase then your query would look like,
SELECT id AS ID FROM person WHERE name = "Dave";
You can do something like this:
public String queryText(final String message, final String... args) {
return String.format(message.toUpperCase().replace("?", "%s") + "%n", args);
}
And call it this way:
System.out.println(queryText("select id from person where name=?", "Dave"));
Output: SELECT ID FROM PERSON WHERE NAME=Dave
Hope it helps

Insert integer from a jsp form into a database table?

See my code below...
//connect
//reading params from the form
String name = request.getParameter("name");
String year_prime = request.getParameter("year");
int year = Integer.parseInt(year_prime);
//inserting the params into table Students
stmt.executeUpdate("insert into students(name,year) values('"+name+"', year)");
//close connection
I am trying to get the year value, which is an int, and insert it into a database table. However I am getting an error, and the INSERT methods only seem to work with Strings. Could someone please help me with this problem.
You should have to use PreapredStatement. From your post I can see you have incorrect value for VALUES() set.
stmt.executeUpdate("insert into students(name,year) values ('" + name + "'," + year ")");
It will be easy and safe to perform database operation with PreparedStatement:
String sql="insert into students(name,year) values (?,?)";
PreparedStatement statement=cn.prepareStatement(sql);
statement.setString(1,name);
statement.setInt(2,year);
statement.executeUpdate();
The following links might help you with the basics and also with a working example:
http://www.tutorialspoint.com/jdbc/jdbc-statements.htm
http://www.tutorialspoint.com/jdbc/statement-object-example.htm
Though I won't recommend and it is also not a general practice to include JDBC connection code in JSP, why? Here is the Servlets and Jsp Best Practices for you.
Hope this helps.
Use a PreparedStatement instead of a regular Statement. Also, use executeQuery() instead of executeUpdate().

Oracle & java dynamic 'Order by' clause

I am trying to build a dynamic sql query in java (shown below)
sqlStr = "Select * " +
"from " + tableName
if(tableName!=null){
if(tableName.equals("Table1"){
sqlStr = sqlStr.concat("order by city desc");
}else if(tableName.equals("Table2"){
sqlStr = sqlStr.concat("order by country desc");
}else if(tableName.equals("Table3"){
sqlStr = sqlStr.concat("order by price desc");
}
}
Now what i would like to do is to add a final 'else' statement which would order the query based on whether the table contains a column named 'custID'. There will be several tables with that column so i want to sort the ones that have that column by custID. (Rather than having hundreds of additional if statements for each table that does have that column name.) Is this possible? i have seen people using the 'decode' function but i cant work out how to use it here.
Use DatabaseMetaData to get the table information.
You can use the getTablexxx() and getColumnxx() methods to get the table information.
Connection conn = DriverManager.getConnection(.....);
DatabaseMetaData dbmd = conn.getMetaData();
dbmd.getxxxx();
Note: you forgot space in your code before ORDER BY clause.
If you are happy with hardcoding things, a way to avoid multiple conditionals would be to store a list of all the tables that include custID.
private final static String tablesWithCustID = "/TableX/TableY/TableZ/";
...
if (tablesWithCustID.contains( tableName )) {
sqlStr = sqlStr.concat("order by custID")
}
You could use a List instead of a simple delimited string if you like.
Perhaps better, you could store a map with table names as the key, and the sort string as the value. Load it up once, then you don't need any conditional at all.
The most straight-forward way to do it is to read the column definitions from USER_TAB_COLUMNS or ALL_TAB_COLUMNS and check for the existence of a custID column. Without crazy PL/SQL tricks, you won't be able to solve this in SQL alone.
BTW, there is a " " missing between tableName and the order by clauses.
I understand that you're looking for a solution that can do this in one query, i.e. without running a separate metadata query beforehand.
Unfortunately, this won't be possible. The decode function can do some dynamic things with column values, but not with column name. And you're looking for a solution dynamically derive the column name.
An alternative might be to just add ORDER BY 1, 2. This is an old syntax that means order by the first and than by the second column. It might be a good solution if the custID column is the first column. Otherwise it at least gives you some sorting.
How about ArrayList.contains()?
You can create a list of tables which have that column, and just check for tables.contains(tablename) in the final if condition.

Variable column names using prepared statements

I was wondering if there was any way to specify returned column names using prepared statements.
I am using MySQL and Java.
When I try it:
String columnNames="d,e,f"; //Actually from the user...
String name = "some_table"; //From user...
String query = "SELECT a,b,c,? FROM " + name + " WHERE d=?";//...
stmt = conn.prepareStatement(query);
stmt.setString(1, columnNames);
stmt.setString(2, "x");
I get this type of statement (printing right before execution).
SELECT a,b,c,'d,e,f' FROM some_table WHERE d='x'
I would, however, like to see:
SELECT a,b,c,d,e,f FROM some_table WHERE d='x'
I know that I cannot do this for table names, as discussed
here, but was wondering if there was some way to do it for column names.
If there is not, then I will just have to try and make sure that I sanitize the input so it doesn't lead to SQL injection vulnerabilities.
This indicates a bad DB design. The user shouldn't need to know about the column names. Create a real DB column which holds those "column names" and store the data along it instead.
And any way, no, you cannot set column names as PreparedStatement values. You can only set column values as PreparedStatement values
If you'd like to continue in this direction, you need to sanitize the column names (to avoid SQL Injection) and concatenate/build the SQL string yourself. Quote the separate column names and use String#replace() to escape the same quote inside the column name.
Prepare a whitelist of allowed column names. Use the 'query' to look up in the whitelist to see if the column name is there. If not, reject the query.
For MySQL prepared statements with NodeJS (mysqljs/mysql), what you need to know is that ? is for values, but if you need to escape column names, table names etc, use ?? instead.
Something like this will work:
SELECT ??, ??, ?? FROM ?? WHERE ?? < ?
Set values to ['id', 'name', 'address', 'user', 'id', 100]
I think this case can't work because the whole point of the prepared statement is to prevent the user from putting in unescaped query bits - so you're always going to have the text quoted or escaped.
You'll need to sanitize this input in Java if you want to affect the query structure safely.
Use sql injection disadvantage of Statement Interface as advantage.
Ex:
st=conn.createStatement();
String columnName="name";
rs=st.executeQuery("select "+ columnName+" from ad_org ");
public void MethodName(String strFieldName1, String strFieldName2, String strTableName)
{
//Code to connect with database
String strSQLQuery=String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);
st=conn.createStatement();
rs=st.executeQuery(strSQLQuery);
//rest code
}
Below is the solution in java.
String strSelectString = String.format("select %s, %s from %s", strFieldName, strFieldName2, strTableName);

Categories