I'm working on a java application, and I want to display the list of the tables in a Mysql database, I searched on the net and I found that "SHOW TABLES FROM [DB]" is the appropriate request, but how can I dispaly the result of this last on a java swing/awt application,
PS : I tried to put the result of the request on a resultset,
res = sta.executeQuery("SHOW TABLES FROM sinpec ");
but it doesnt work ...
How can I proceed ?
Please try this query:-
SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE table_schema = "DATABASE_NAME"
According to this blog, you could use the following statement:
SELECT table_name FROM information_schema.tables WHERE table_type = 'base table' AND table_schema='test';
Which seems to have a similar effect to that of SHOW TABLES.
This should work with the result result that you are using.
This example may help you. Basically you can use DatabaseMetaData class to full fill your task.
public static String SCHEMA_NAME="${YOUR_SCHEMA_NAME}";
public static void main(String[] args) {
//create and setup your database and get db connection
DataBase db = new DataBase();
db.init();
try {
Connection con = db.getConnection();
DatabaseMetaData metaData = con.getMetaData();
String tableType[] = {"TABLE"};
StringBuilder builder = new StringBuilder();
ResultSet result = metaData.getTables(null,SCHEMA_NAME,null,tableType);
while(result.next())
{
String tableName = result.getString(3);
builder.append(tableName + "( ");
ResultSet columns = metaData.getColumns(null,null,tableName,null);
while(columns.next())
{
String columnName = columns.getString(4);
builder.append(columnName);
builder.append(",");
}
builder.deleteCharAt(builder.lastIndexOf(","));
builder.append(" )");
builder.append("\n");
builder.append("----------------");
builder.append("\n");
}
System.out.println(builder.toString());
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can try this solution it shows all the tables
try {
DbMd = myconn.getMetaData();
Rslt = DbMd.getTables(null, null, "%", null);
while (Rslt.next()) {
System.out.println(Rslt.getString(3));
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Related
I wanted to know how to view tables from both schemas (in this example lets say world and world2), through JSF. I can log into my application using a specified schema and view the tables from that schema but I do not know how to log in and view a different schema. (ex. log in as world, view world2 schema table names.)
So I want to ask if there is a way to rewrite tablelist, or maybe repurpose the code to handle sql queries even though the connection is for a specific schema.
Currently I am using:
public TableList[] getTableList() {
try {
String[] TABLE_TYPES = { "TABLE", "VIEW" };
DatabaseMetaData databaseMetaData;
String query = "";
// st = conn.createStatement();
st = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
databaseMetaData = conn.getMetaData();
rs = databaseMetaData.getTables(null, dbaseBean.getUserName(),
null, TABLE_TYPES);
rs.last();
int count = rs.getRow();
tableList = new TableList[count];
rs.beforeFirst();
int i = 0;
while (rs.next()) {
tableList[i] = new TableList(rs.getString("TABLE_NAME"));
i++;
}
} catch (Exception e) {
e.printStackTrace();
FacesMessage msg = new FacesMessage("" + " Error Occured");
FacesContext.getCurrentInstance().addMessage(null, msg);
}
setTableList(tableList);
return tableList;
}
With the following connection:
public boolean connect() {
FacesContext context = FacesContext.getCurrentInstance();
Map<String, Object> m = context.getExternalContext().getSessionMap();
messageBean = (MessageBean) m.get("messageBean");
dbmsUserBean = (DbmsUserBean) m.get("dbmsUserBean");
userName = dbmsUserBean.getUserName();
password = dbmsUserBean.getPassword();
switch (dbmsUserBean.getDbms().toLowerCase()) {
case "mysql":
jdbcDriver = "com.mysql.jdbc.Driver";
url = "jdbc:mysql://" + dbmsUserBean.getDbmsHost() + ":3306/"
+ dbmsUserBean.getDatabaseSchema();
break;
case "db2":
jdbcDriver = "com.ibm.db2.jcc.DB2Driver";
url = "jdbc:db2://" + dbmsUserBean.getDbmsHost() + ":50000/"
+ dbmsUserBean.getDatabaseSchema();
userName = userName.toUpperCase();
break;
case "oracle":
jdbcDriver = "oracle.jdbc.driver.OracleDriver";
url = "jdbc:oracle:thin:#" + dbmsUserBean.getDbmsHost() + ":1521:"
+ dbmsUserBean.getDatabaseSchema();
userName = userName.toUpperCase();
break;
case "odbc":
default:
//
break;
} // end switch
try {
// register driver
Class.forName(jdbcDriver);
// get connection
connection = DriverManager.getConnection(url, userName, password);
// get SQL statement object instance
statement = connection.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
// retrieve DB meta data
databaseMetaData = connection.getMetaData();
DbaseBean dbaseBean = new DbaseBean();
dbaseBean.setConnection(connection);
dbaseBean.setDatabaseMetaData(databaseMetaData);
dbaseBean.setJdbcDriver(jdbcDriver);
dbaseBean.setUserName(userName);
dbaseBean.setPassword(password);
dbaseBean.setUrl(url);
dbaseBean.setResultSet(resultSet);
m.put("dbaseBean", dbaseBean);
status = true;
}
catch (ClassNotFoundException e) {
// assumes there is a corresponding printException method
// PrintException("Connect: Class not found Exception - could not loadJDBC driver");
status = false;
}
catch (SQLException e) {
// printException(e,"Connect: SQLException information");
status = false;
} catch (Exception e) {
// printException(e,"Connect: Exception information");
status = false;
}
return status;
}
Thank you.
If you are going against Oracle and you have access to the system tables, you can retrieve tables from it with "select user, table_name from system.all_tables where user in ('myuser1', 'myuser2');"
If you want everything, you can go against all_objects where type in 'TABLE', 'VIEW' (and procedure and trigger and...)
If you are going against different databases, you would then have to determine where and what the data dictionaries for each DB are and write code for each one.
DOH - You stated MySQL in the title:
select table_schema, table_name from INFORMATION_SCHEMA.TABLES where table_schema in ('myfirstone', 'mysecondone');
I've spent a few hours researching on how to create a Java method that will help with my program. I am very new to MySQL, so I am not the most experienced person out there.
What I am trying to do is write a Java method that checks if a column that has the is named after a username exists inside of a table. If it does not exists, it will create that column.
I have seen lot's of tutorials on the internet about similar solutions to my problem. I don't see how I am supposed to implement the TABLE_SCHEMA into a java method since I only know the very basics of MySql.
It would be nice to see how to implement this or some other solution into the Java method. I've mostly erased my previous work since I could not figure it out, so sorry if I need to show that(This is my first question.)
Edit:
try {
ResultSet res = conn.createStatement()
.executeQuery("ALTER TABLE `package_table` ADD " + username + " VARCHAR(15);");
if (!res.next()) {
conn.createStatement()
.executeUpdate("INSERT INTO `package_table` (`uuid`, `name`, `packages`) VALUE ('"
+ event.getPlayer().getUniqueId() + "', '" + event.getPlayer().getName() + "', '" + "" + "');");
}
} catch (SQLException e) {
e.printStackTrace();
try {
conn.close();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Edit2:
The reason I need to do columns is that I need to store the 'packages' a username has. There can be "infinite" amounts of packages.
Thanks,
Jack
You can do it using jdbc. Just get column names and then add one if you need.
Something like this:
Connection con;
Statement st;
ResultSet rs;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/dbname",
"dbuser",
"bdpass"
);
st = con.createStatement();
String sql = "select * from table";
rs = st.executeQuery(sql);
ResultSetMetaData metaData = rs.getMetaData();
int rowCount = metaData.getColumnCount();
boolean isMyColumnPresent = false;
String myColumnName = "myColumnName";
for (int i = 1; i <= rowCount; i++) {
if (myColumnName.equals(metaData.getColumnName(i))) {
isMyColumnPresent = true;
}
}
if (!isMyColumnPresent) {
String myColumnType = "some type";
st.executeUpdate("ALTER TABLE table ADD " + myColumnName + " " + myColumnType);
}
} catch (Exception e) {
e.printStackTrace();
}
You can do something like this,
DatabaseMetaData metadata = conn.getMetaData();
Resultset rs = null;
rs=metadata.getColumns(null, null, "package_table", null);
boolean found=false;
while (rs.next()) {
if(username.equals(rs.getString("COLUMN_NAME"))
{
found=true;
}
}
if(found){
//Skip column creation
}else{
//Create column
}
No error is showing when i click the button but the table on the database doesn't update.
String heh = jLabel17.getText();
try {
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch (SQLException err) {
System.out.println(err.getMessage() );
}
You have messed up the query totally,
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
should be,
stmt.executeUpdate("UPDATE books SET availability='Unavailable' where Book_title='"+heh+"' ");
It is advisable to print query before you execute , as that avoids common mistakes. Also try to use Prepared Statements as yours is vulnerable to sql injection
Read this Prepared Statements and JDBC Drivers
AFTER HOURS OF RESEARCH, I FOUND THE SOLUTION, I REPLACED THIS
String heh = jLabel17.getText();
try{
stmt.executeUpdate("UPDATE books SET availability='"+"Unavailable"+"' where Book_title='"+heh+"'");
}catch(SQLException err){
System.out.println(err);
}
WITH THIS CODE
String heh = jLabel17.getText();
try{
con = DriverManager.getConnection("jdbc:derby://localhost:1527/Dafuq7","Dafuq7","Dafuq7");
// Creating Statement for query execution
stmt = con.createStatement();
// creating Query String
String query = "UPDATE books SET availability='NOT AVAILABLE' WHERE book_title='"+heh+"'";
// Updating Table
int rows = stmt.executeUpdate(query);
System.out.println(rows + " Rows Updated Successfully....");
} catch (Exception e) {
System.out.println(e.toString());
}
I am having many rows in table and I ran the same query on my database which is MySql but java ResultSet is only giving the first row of the table. Here is my code.
public ArrayList<String> getAllAlbumsName(Integer uid) {
ArrayList<String>allAlbumsName = new ArrayList<String>();
try {
String qstring = "SELECT albumname FROM picvik_picture_album WHERE " +
"uid = '" + uid + "';";
System.out.println(qstring);
connection = com.picvik.util.MySqlConnection.getInstance().getConnection();
ptmt = connection.prepareStatement(qstring);
resultSet = ptmt.executeQuery();
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
resultSet.close();
ptmt.close();
connection.close();
} catch (Exception e) {
e.printStackTrace();
}
return allAlbumsName;
}
if(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
If you would like to get all rows, it should be:
while(resultSet.next()) {
System.out.println(resultSet.getString("albumname"));
allAlbumsName.add(resultSet.getString("albumname"));
}
The while statement continually executes a block of statements while a particular condition is true
Note: As #BalusC commented, your code would introduce SQL Injection attack, it is better to use ptmt.set... Instead of constructing SQL String manually.
try while(resultSet.next()) {
instead of if (resultSet.next()) {
Change if (resultSet.next()) { to while (resultSet.next()) {
Here's my static utility:
//String sqlQuery = "select count(name) as num from tbname where name = ?"
//String name = "testString";
private static int correct(Connection connection, String sqlQuery, String name) {
int result = 0;
PreparedStatement statatement = null;
ResultSet rs = null;
try {
statatement = connection.prepareStatement(sqlQuery);
statatement.setString(1, name);
rs = statatement.executeQuery();
while (rs.next()) {
result = rs.getInt("num");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
statatement.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
}
The method above returns 0 (incorrect result), but the following one returns '1' (it works OK, it the same sql query):
//String sqlQuery = "select count(name) as num from tbname where name = 'testString'"
private static int correct(Connection connection, String sqlQuery, String name) {
int result = 0;
PreparedStatement statatement = null;
ResultSet rs = null;
try {
statatement = connection.prepareStatement(sqlQuery);
rs = statatement.executeQuery();
while (rs.next()) {
result = rs.getInt("num");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
statatement.close();
} catch (SQLException e) {
throw new RuntimeException(e.getMessage());
}
return result;
}
}
Could you please give me any advise, so I could resolve the problem.
PS: I'm not sure if it does matter, but the actual streetName - has a name in windows-1251 encoding (Russian) text.
PPS: The database is Oracle 10.
It might be a character set issue. According to the Oracle JDBC Drivers release 10.1.0.2.0 (10g) README:
The following is a list of known
problems/limitations:
If the database character set is AL32UTF8, you may see errors under the
following circumstances:
accessing LONG and VARCHAR2 datatypes.
binding data with setString() and setCharacterStream().
So if your database character set is AL32UTF8, you might have to get it changed to something else.
Also, what is the datatype of your column? VARCHAR2?
It seems the encoding conflict with the one which you set in your DB encoding charset and the the String you are passing..
You can do these 2 tries
Set the DB encoding to UTF-8 and then give a try. If this does not work you may go with following 2nd option
Set DB encoding charset to UTF-8 and also set the String by using this String constructor String(byte[] bytes, String charsetName)