i have two tables "Table1" with columns user_name,Password and course ID and another table "course" with columns course_id,course_name.I have used the following code to display the course ID from Table1 according to the user_name received from the login page.using ResultSet rs1.now i want to retrieve the course_name from the table "course" according to the course ID receieve from "Table1".for that in the second query pstmt2.setString(1, ); what parameter i should use to get the course_id value from the previous query
HttpSession sess=request.getSession();
String a=(String)sess.getAttribute("user");
String b=(String)sess.getAttribute("pass");
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con=DriverManager.getConnection("jdbc:odbc:ggg");
Statement st = con.createStatement();
String query="select * from Table1 where user_name=?";
PreparedStatement pstmt=con.prepareStatement(query);
pstmt.setString(1,a);
ResultSet rs1=pstmt.executeQuery();
while(rs1.next())
out.println("<h3>COURSE ID: "+rs1.getString("course ID")+"<h3>");
String query2="SELECT * from course where course_id=?";
PreparedStatement pstmt2=con.prepareStatement(query2);
pstmt2.setString(1,);
ResultSet rs2=pstmt2.executeQuery();
while(rs2.next())
{
out.println("<h3>course name: "+rs2.getString("course_name")+"<h3>");
}
why do you go for two turns of database hit, even though you created one time connection object.
modify the query as below
SELECT * from course where course_id = (select course_id from Table1 where user_name=?);
from this query you noneed to give input of courseid also.
No need to hit database twice to get the results that you need. use the query
Select table1.course_id, course.course_name from table1, course where table1.course_id=course_id and table1.user_name=?
This should set the course_id parameter:
pstmt2.setString(1,rs1.getString("course_id"));
Or, as I see the "course_id" column may have a different name in "Table1":
pstmt2.setString(1,rs1.getString("course ID"));
As the other post mentioned there's no need to go to another set of query. Try this example query:
SELECT course.course_id, course.course_name
FROM table1 t1
INNER JOIN course c
ON t1.course_id = c.course_id
WHERE t1.user_name = ?;
Now if you insist your coding the parameter o your pstmt2.setString(1,); is:
pstmt2.setString(1,rs1.getString("course_id")); //or course ID defending on your column name
Related
I want to use jdbcTemplate to create table based on another table under condition. I have postgres database. When I execute this and pass parameter:
String SQL = "create table test as (select * from users where countryId =?)";
jdbcTemplate.update(SQL, new Object[] {3})
I receive table test with all columns from users table but with no rows.
However, when I execute this:
String SQL = "create table test as (select * from users where countryId =3)";
jdbcTemplate.update(SQL)
I receive test table with rows where countryId = 3, so that is what I was expecting to receive in the first solution.
Your passing of the bind variable is not correct, but it does not play any role.
You simple can not use a bind variable in a data definition statement as you immediately see in the triggered error
Caught: org.springframework.jdbc.UncategorizedSQLException:
PreparedStatementCallback; uncategorized SQLException for SQL
[create table test as (select * from users where countryId =?)];
SQL state [72000]; error code [1027];
ORA-01027: bind variables not allowed for data definition operations
So you have two options, either concatenate the statement (which is not recommended due to the danger of SQL injection)
or split the statement in two parts:
// create empty table
sql = "create table test as (select * from users where 1 = 0)";
jdbcTemplate.update(sql)
// insert data
sql = "insert into test(countryId, name) select countryId, name from users where countryId =?";
updCnt = jdbcTemplate.update(sql, new SqlParameterValue(Types.INTEGER,3));
Note that in the insert statement you can see the correct way of passing an interger value of 3 as a bind variable.
You can follow below approach as well:-
jdbcTemplate.execute("CREATE TABLE IF NOT EXISTS employee_tmp (id INT NOT NULL)");
List<Object[]> employeeIds = new ArrayList<>();
for (Integer id : ids) {
employeeIds.add(new Object[] { id });
}
jdbcTemplate.batchUpdate("INSERT INTO employee_tmp VALUES(?)", employeeIds);
Here you may query with 2 operations to avoid SQL injection.
You are using method update from jdbcTemplate in a wrong way.
Try with this:
String SQL = "create table test as (select * from users where countryId = ?)";
jdbcTemplate.update(SQL, 3);
I have a jComboBox which i want to fill up with the departments of the students in a database. Now the same department occurs many times in the table so i want each department name to go only once to the list of items. The present code i wrote is not giving the desired result. It puts the same department name multiple times on the ComboBox list. How can i solve this?
My code to fetch department names is given below:
conn=DriverManager.getConnection("jdbc:mysql://localhost:3306/mydaatabase1","root","Password123");
String sql1 = "select distinct (dept) from droptest";
PreparedStatement pss = conn.prepareStatement(sql1);
ResultSet rs = pss.executeQuery(sql1);
while(rs.next())
{
String d = rs.getString("dept");
jComboBox1.addItem(d);
}
I guess, you need use group by in select data...
select columnName
from tablename
Group by columnName
Select dept
From droptest
Group by dept
Group by is like distinct
I want to write an insert query using preparedStatement. Inside it I want to put a selection query. I did the following but I get: You have an error in your SQL syntax
protected final String createStudentQuery = " INSERT INTO student (student_id, ed_level) VALUES (SELECT MAX(user_id) FROM user WHERE usertype ='Student' , ?)";
and then
stmt5 = conn.prepareStatement(createStudentQuery);
stmt5.setString(1, ed_level);
stmt5.executeUpdate();
All the declarations(connection, statement) have been made.
There are 2 values that needs to be inserted, student_id and ed_level . But in your select statement there is only one value, MAX(user_id). You have to also add the value for ed_level in the select query.
Also, your query should be:
INSERT INTO <TABLE_1> (COLUMN_1, COLUMN_2,...) SELECT COLUMN_1, COLUMN_2,... FROM <TABLE_2> WHERE <CONDITION>
I have modified the query to something like this:
INSERT INTO student (student_id, ed_level) VALUES ((SELECT MAX(user_id) FROM user WHERE usertype ='Student') , ?)
Hope this helps.
I have a query using various joins, and I just need the list of columns which are returned by this query. I done it in java, by asking only one row with rownum=1 and getting column name for value.The problem is if there is no data returned by that query.
For ex.
select * from something
and if there is any data returning by this query then it will return col1,col2,col3.
But if there is no data returned by this query, then it will throw error.
What I need is
Is there any way that I can run
desc (select * from something)
or similar to get list of columns returned by query.
It can be in sql or JAVA. Both methods are acceptable.
In my application, user passes the query, and I can add wrapper to the query but I cant modify it totally.
The flow of application is
query from user -> execute by java and get one row -> return list of columns in the result set.
you can use ResultSetMetaData of resultset
for example :
ResultSet rs = stmt.executeQuery("SELECT a, b, c FROM TABLE2");
ResultSetMetaData rsmd = rs.getMetaData();
int countOfColumns = rsmd.getColumnCount();
for(int i = 1; i <= countOfColumns ; i++ )
System.out.println(rsmd.getColumnName(i));
you could maybe convert your query to a view, you can then see the columns in the view by querying user_tab_columns
select * from user_tab_columns
The Oracle equivalent for information_schema.COLUMNS is USER_TAB_COLS for tables owned by the current user, ALL_TAB_COLS or DBA_TAB_COLS for tables owned by all users.
Tablespace is not equivalent to a schema, neither do you have to provide the tablespace name.
Providing the schema/username would be of use if you want to query ALL_TAB_COLS or DBA_TAB_COLS for columns OF tables owned by a specific user. in your case, I'd imagine the query would look something like:
String sqlStr= "
SELECT column_name
FROM all_tab_cols
WHERE table_name = 'users'
AND owner = ' || +_db+ || '
AND column_name NOT IN ( 'password', 'version', 'id' )
"
Note that with this approach, you risk SQL injection.
Greeting to all smart people around here !!
I have faced a weird interview question regarding SQL.
Qn . If I have 100 tables in Database. I want to fetch common records from Each table.
For example, location is common field in 100 tables. I want to fetch location field from all the tables without mentioning each table name in my SQL query.
Is there any way to do it?
If any possibilities let me know...
get list of tables from db metadata, and then query with each:
Statement stmt = conn.createStatement();
ResultSet locationRs = null;
DatabaseMetaData md = conn.getMetaData();
ResultSet rs = md.getTables(null, null, "%", null);
while (rs.next()) {
locationRs = stmt.executeQuery("SELECT location from "+ rs.getString(3));
System.out.println(locationRs.getString(1));
}
In MSSQL Server you have INFORMATION_SCHEMA.COLUMNS table that contains the column names so you can use group by and having count some value you will get the column name after that you can use pivot to get the values of column names and carry on to it. You will get the ans.
For eg.
Select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS group BY COLUMN_NAME having count(COLUMN_NAME) > 2
By above query you will get the common column names
You can try this for any Number of Tables in a DB :
select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS group by COLUMN_NAME having count(COLUMN_NAME)=(select count(*) from INFORMATION_SCHEMA.TABLES)
My friend has found answer for my question..
To get common column from multiple tables,Use INFORMATION_SCHEMA.COLUMNS and common column name.
Query :
select *from information_schema.columns where column_name='column name'
Hope this will helpful !
I am assuming you already have connection and statemnt object's. Now try the below; it might work for you, if not make some adjustments with loops and conditions. Also, you need to have two ResultSet Objects ex: rs1 and rs2. DatabaseMetaData dbmd = con.getMetaData();
String table[] = {"TABLE"} `;
rs1 = dbmd.getTable(null, null, ".*" ,table);
while(rs1.next()){
String tableFrom = rs1.getString(3) ;
rs2 = dbmd.getColumns(null,null,tableFrom , ".*") ;
while(rs2.next()) {
String locColFrom = rs2.getString(3);
if(locColFrom .equalsIgnoreCase("location"))
stmt.executeQuery(select locColFrom from tableFrom ) ;
}
}
Here's an link to study [Oracle] (http://docs.oracle.com/javase/7/docs/api/java/sql/DatabaseMetaData.html#getTables(java.lang.String,%20java.lang.String,%20java.lang.String,%20java.lang.String[]))