How to execute MySQL query, "show tables;" inside a Java Program..? - java

I am a newbie to Java and MySQL. Please pardon me if my question seems silly, I want to know the answer...
I have gone through many articles and questions asked in forums, but I didn't see a relevant answer for my question...
That is, I have made a switch statement in Java and I want to show the list of available tables in a database if I press 1( that is go into the case 1 and execute a query "show tables;" )
In MySQL Console, it is easy to check for available tables using the same query. But I want to know whether "show tables;" query or similar queries can be executed inside a Java Program...
Here's a sample snippet of my code,
Connection con=null;
String url = "jdbc:mysql://localhost:3306/giftson";
String dbName = "giftson";
String userName = "root";
String password = "password";
con=DriverManager.getConnection(url,userName,password);
Statement st=con.createStatement();
//String query;
Statement st=con.createStatement();
System.out.println("\tDatabase Connection for Various Operations");
System.out.println("\n1. Show list of tables\n2. Show contents of Table\n3. Create New Table\n4. Insert into table\n5. Update Table\n6. Delete From Table\n7. Exit\n");
System.out.println("Enter your option Number ");
DataInputStream dis=new DataInputStream(System.in);
int ch=Integer.parseInt(dis.readLine());
switch(ch)
{
case 1:
System.out.println(" You have selected to Show list of available tables");
//ResultSet rs=st.executeQuery("Show tables");
//while(rs.next())
//{
// System.out.println("List of Tables\n" +rs.getString("?????"));
//}
break;
}
from the above piece of code,
If I execute the query in ResultSet, How do I print the values inside the while loop..?
In rs.getString(); we can only pass either the column index or the column label as argument, but how do I get the list of tables...
what do I enter in place of "?????" inside print statement...?
please do help me, keeping in mind that you are explaining for a beginner...
Thanks in advance...!

We can use the console commands using,
DatabaseMetaData meta=getMetaData();
In the below code, it is shown that there are many ways (but I came to know two ways) of getting the list of tables
DatabaseMetaData meta = con.getMetaData();
ResultSet rs1 = meta.getTables(null, null, null,new String[] {"TABLE"});
ResultSet rs2 = meta.getTables(null, null,"%", null);
System.out.println("One way of Listing Tables");
while (rs1.next())
{
System.out.println(rs1.getString("TABLE_NAME"));
}
System.out.println("Another way of Listing Tables");
while(rs2.next())
{
System.out.println(rs2.getString(3));
}

A small example would be
String tableNamePattern = "%_Assessment_" + session + "_" + year;
DatabaseMetaData databaseMetaData = conn.getMetaData();
ResultSet rs = databaseMetaData.getTables(null, null, tableNamePattern,
null);
while(rs.next()) {
String tableName = rs.getString("TABLE_NAME");
...
}
Check the source

Related

How to parse values for the result set's .equals function?

image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}

Best way to check if the record is exist

what is the best way to check if the user is exist
i have wrote this code
try{
PreparedStatment mPre=conn.preparedStatement(INSERT INTO TABLE VALUES(?,?);
}catch(Exception e)
{
if(e.getMessage().contains("Dublicated"))
{
throw new Exception("user is exist");
}
}finally {
mPre.close();
conn.close();
}
my friends told me that this is stupid query
and i should do like this
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("SELECT COUNT(*) AS total FROM .......");
int cnt = rs.getInt("total");
Your friend is right. You can check if row exists by query:
SELECT EXISTS(SELECT 1 FROM *table* WHERE *something*)
As long as you are trying to insert a row that breaks the unique primary key constraint of database tables AND the exception thrown has a stack trace that contains the word "duplicated" then your code should work fine.
But in the unlikely event that the stack trace changes and does NOT contain that word, your code won't work anymore.
It's more likely that you are trying to insert a row with a unique primary key value but an existing username, which won't give you the error that you hope for. That's the reason why it would be smarter/safer to retrieve results for that username and count how many results there are.
When you are trying to verify if the given username and password exists in your user table, you should use PreparedStatment because it will help you in protecting your application from SQL injection.
But
Inserting a new user to the database is not the right way to do user validation.
You can do something like this example:
String selectSQL = "SELECT * FROM USER_TABLE WHERE USER_ID = ? AND PASSWORD = ?";
PreparedStatement preparedStatement = dbConnection.prepareStatement(selectSQL);
preparedStatement.setInt(1, 1001);
preparedStatement.setString(2, "1234");
ResultSet rs = preparedStatement.executeQuery(selectSQL );
while (rs.next()) {
//You will need user information to render dashborad of your web application
String userid = rs.getString("USER_ID");
String username = rs.getString("USERNAME");
}
Complete code refrence: http://www.mkyong.com/jdbc/jdbc-preparestatement-example-select-list-of-the-records/

Operation not allowed after ResultSet Closed error Netbeans MySQL Connectivity

I am creating a program to rename databases in mysql.
I have succeeded in everything and it successfully happens. But in the end of my script, its shows an error/exception saying "Operation not allowed after ResultSet closed". I really have no idea why this error appears even after researching about this error.
Although the full operation is successfully completed and the database is renamed.
Here is my code->
String x = (String) jComboBox1.getSelectedItem(); //jComboBox1 contains the name of current database selected
String z = JOptionPane.showInputDialog("Please enter new name for Database"); //Where user enters the name for new database.
new CustComm().setVisible(false); //Frame that carries the names of tables.
try{
Class.forName("java.sql.DriverManager");
Connection con = (Connection)
DriverManager.getConnection("jdbc:mysql://localhost:"+GlobalParams.portvar+"/",""+k,""+j);
Statement stmnt = (Statement) con.createStatement();
String query = "use "+x;
stmnt.executeQuery(query);
String query2 = "show tables";
ResultSet rs = stmnt.executeQuery(query2);
while (rs.next()){
String dname = rs.getString("Tables_in_"+x);
if(CustComm.jTextArea1.getText().equals("")){
CustComm.jTextArea1.setText(CustComm.jTextArea1.getText()+dname);
}
else{
CustComm.jTextArea1.setText(CustComm.jTextArea1.getText()+"\n"+dname);
}
String y = CustComm.jTextArea1.getText();
Scanner scanner = new Scanner(y);
while (scanner.hasNextLine()) {
String line = scanner.nextLine();
String query3 = "Create database "+z;
stmnt.executeUpdate(query3);
//alter table my_old_db.mytable rename my_new_db.mytable
String query4 = "RENAME TABLE "+x+"."+line+" TO "+z+"."+line;
stmnt.executeUpdate(query4);
String query5 = "drop database "+x;
stmnt.executeUpdate(query5);
}}}
catch(Exception e){
JOptionPane.showMessageDialog(this,e.getMessage());
}
Please help.
You shouldn't execute new queries on statement Statement stmnt = (Statement) con.createStatement(); while you use ResultSet from it, because this will close your ResultSet.
By default, only one ResultSet object per Statement object can be open
at the same time. Therefore, if the reading of one ResultSet object is
interleaved with the reading of another, each must have been generated
by different Statement objects. All execution methods in the Statement
interface implicitly close a statment's current ResultSet object if an
open one exists.
You should create 2 different statements: first for query2 and second for queries 3-5.
Also it's better to use PreparedStatement. You can read about the difference here.
Do you have to do this work via code? Have you looked into tools like Liquibase?

my sql query don't work

i have one problem with database in java
my code is ( its only one small part of my project)
public void Read_from_DB(int exhibition_id){
Statement stmt = null;
Connection connect = null;
try {
connect=MYConnection.new_connection();
stmt = connect.createStatement();
QuestionCatalog.get_QuestionCatalog_instance().setShow_quest(new ArrayList<Question>());
String sql = "SELECT * FROM question WHERE Selection=0 AND exhibition_id="+exhibition_id;
//System.out.println(sql);
ResultSet rs = stmt.executeQuery(sql);
System.out.println("!");
System.out.println("->"+rs.getFetchSize());
while(rs.next()){
Question jd=new Question();
System.out.println("!!!");
jd.setQuestion_id(rs.getInt("Question_id"));
jd.setQuestion(rs.getString("Question"));
jd.setQuestion(rs.getString(exhibition_id));
jd.getOption_2().setContent(rs.getString("Content2"));
QuestionCatalog.get_QuestionCatalog_instance().getShow_quest().add(jd);
System.out.println("size"+QuestionCatalog.get_QuestionCatalog_instance().getShow_quest().size());
MYConnection.close_connection(stmt, connect);
}
}catch (Exception e) {
}
}
when i execute this code it dosent work
my database table name is "question"
but when i change the name in this query to "Question" , don't get any error
then i think it doesn't execute my query,my main is
public static void main(String[] args) {
DB_question d=new DB_question();
d.Read_from_DB(1);
}
and "MYConnection.new_connection();" in part on of code return a connection,( i test it in another class it work)
the result in console is :
SELECT * FROM Question WHERE Selection=0 AND exhibition_id=1
!
->0
it haven't show "!!!"that is result of "System.out.println("!!!");"
then i think it doesnt work :|
thanks
p.s the picture of my db
picture
What I understand from your question is improper output on case sensitive names on table names or column names. Am I right?
As far as I know, reserved words like SELECT, FROM, etc. are case in-sensitive in all OS's. And all other user defined object names are case-sensitive, in *ix OS environment. But not in in Windows OS environment.
But all RDBMS configurations should be allowing case-insensitivity for cross platform deployment. This is the reason why your change from question to Question did not throw an error.
And regarding the outcome of your query:
I fear you have tested your query on different databases or servers. They might not have same data and hence always not entering into while( rs.... loop.
Change your code as below and see what the output is:
ResultSet rs = stmt.executeQuery(sql);
System.out.println("!");
System.out.println("->"+rs.getFetchSize());
rs.beforeFirst();
rs.last();
int rowCount = rs.getRow();
System.out.println( "---> rowCount: " + rowCount );
rs.beforeFirst();
while( ...
Also refer to:
DBMS Identifiers and Case Sensitivity - MysQL

JAVA: get cell from table of mysql

I get a parameter is called 'id' in my function and want to print the cell of the name of this id row.
for example:
this is my table:
id name email
1 alon alon#gmail.com
I send to my function: func(1), so I want it to print 'alon'.
this is what I tried:
static final String url = "jdbc:mysql://localhost:3306/database_alon";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, "root", "Admin");
String query_txt = "SELECT * FROM authors WHERE id = " + id;
Statement ps2 = con.createStatement();
ResultSet my_rs = ps2.executeQuery(query_txt);
System.out.println(my_rs.getString("name"));
con.close;
Everything is fine, but just one problem. You need to move your ResultSet cursor to the first row before fetching any values: -
Use: -
ResultSet my_rs = ps2.executeQuery(query_txt);
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
As a side note, consider using PreparedStatement to avoid getting attacked by SQL Injection.
Here's how you use it: -
PreparedStatement ps2 = con.prepareStatement("SELECT * FROM authors WHERE id = ?");
ps2.setInt(1, id);
ResultSet my_rs = ps2.executeQuery();
while (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
You need to use ResultSet.next() to navigate into the returned data:
if (my_rs.next()) {
System.out.println(my_rs.getString("name"));
}
Call my_rs.next(), which will move the ResultSet cursor onto the first row (which you are extracting data out of).
If this is a real application, use PreparedStatements instead of generic Statements. This is an extremely important matter of security if you plan on using user input in SQL queries.

Categories