Create new table in SQLite with query result - java

I have this code in Java and i need to insert the result into new table. Is this possible with just editing this query?
ResultSet result = stat.executeQuery("SELECT artist, COUNT(artist) AS countartist FROM table1 GROUP BY artist ORDER BY countartist DESC;");

Try this:
ResultSet result = stat.executeUpdate("CREATE TABLE newtable AS SELECT artist, COUNT(artist) AS countartist FROM table1 GROUP BY artist ORDER BY countartist DESC");

Related

Adding distinct data to jComboBox from database

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

Using Select and where statement in Criteria

I am in the process of replacing jdbc with hibernate in my Web Application. I have learned that i don't have to write any SQL queries in this. Instead of this,criteria queries can help me.
These are my SQL queries which i want to convert to hibernate using criteria not HQL.
String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
rsDeptName = stmt.executeQuery("SELECT DEPARTMENT_NAME FROM DEPARTMENT WHERE DEPARTMENT_ID ="+ DeptID + ";");
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
First off all you must map your table with POJOS.
String getOrgIdQuery = "SELECT * FROM USER_DETAILS WHERE USER_ID= ?";
Preceding code in Hibernate look like following.
Criteria criteria = session.createCriteria(USER_DETAILS.class);
criteria.add(Restrictions.eq("user_id",yourUserId));
List<USER_DETAILS> list = criteria.list();
Your second select query is also same as preceding.
String insertCreateCdcValuesFirst = ("UPDATE User_Details SET User_Name=?, Organization_ID=?, Department_ID=?, Access_Ctrl = ?, User_Role=? WHERE User_ID = ?;");
With Hibernate Criteria update looks like following:
USER_DETAILS user_details = (USER_DETAILES) session.get(USER_DETAILS.class,yourUserId);
user_details.setUser_Name(NewUserName);
user_details.setOrganization_Id(newOrganizationId);
// some other fields update goes here
session.update(user_details);
tx.commit();
I hope this help you.

How to Fetch common column from multiple tables in Database?

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[]))

sql : how can i execute two dependents queries?

I have 2 tables (table1, table2) table1 has a field id and table2 has a field id_eid that reference the id field of table1 as foreign key.
I have to delete from table1 all the rows that match a determinated criteria and then if these data are referenced in table2 delete the data from it too.
I do something like that, assuming con is the Connection object and autocommit is set to false on it.
String query1 = "delete from table2 where exists
(select * from table1 where someparameter = ? and table1.id = table2.id_eid)"
then i execute the first query1 using PreparedStatement.
then i have
String query2 = "delete from table1 where someparameter = ?
and exists (select * from table2 where table1.id = table2.id_eid)"
and i executed this with another PreparedStatment.
at the end i have the con.commit().
This doesn't work, i was thinking using autocommit to false the two queries was executed together but it is not, the second query deletes no rows, how can i do this ?
An important note, not all the rows in table1 have a referenced row in table2.
Thanks
You could always query the data to delete first, then delete it second:
1) Select ID from table1 where <criteria>
2) Select ID from table2 where <criteria>
3) Delete from table1 where ID in <results from (1)>
4) Delete from table2 where ID in <results from (2)>
If you
"have to delete from table1 all the rows that match a determinated criteria"
I think String query2 must be
String query2 = "delete from table1 where someparameter = ?"

problem in setString method.in retrieving data from the table

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

Categories