how can we see output without rectangular boxes - java

i have created a table in data base which consists of telugu data .when i am trying to retrieve telugu data by using eclipse in java i am getting out with rectangular boxes .
code :
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sloka?useUnicode=yes&characterEncoding=UTF-8", "root", "");
st = con.createStatement();
} catch (Exception e) {
System.out.print("error:" + e);
}
public void getData() {
try {
String query = "select * from eesavyasa ";
rs = st.executeQuery(query);
System.out.print("records from database");
while (rs.next()) {
String name1 = new String(rs.getBytes("firstcolumn"), "UTF-8");
String name2 = new String(rs.getBytes("secondcolumn"), "UTF-8");
String name3 = new String(rs.getBytes("thirdcolumn"), "UTF-8");
String name4 = new String(rs.getBytes("fourthcolumn"), "UTF-8");
System.out.println(name1);
System.out.println(name2);
System.out.println(name3);
System.out.println(name4);
}
} catch (Exception ex) {
System.out.print(ex);
}
}
we have used collation utf-8 for db ,table,for all but we are getting output in rectangular boxes
kindly respond as soon as possible

It would be fixed after executing below sql after connected to mysql
SET NAMES utf8

Related

Sign-In as different users types

I'm very new to JAVA so this is probably an easy solution.
I'm looking to design a login system using differnt users from a database.
They are seperated by a "Yes" column in the database.
It currently signs in the manager using the IF statement but stops there and won't sign in when using credetials of a staff member.
signIn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try{
Class.forName(DRIVER);
// Connection to the Database
con = DriverManager.getConnection(DATABASE_URL,"root","");
// Gets text from textfields and assigns them to variables
s1 = tfUsername.getText();
s2 = tfPassword.getText();
Statement st = con.createStatement();
// SQL Statements
st.executeQuery("SELECT * FROM login WHERE UName= '"+s1+"' and PWord = '"+s2+"'");
// Extracts data from statement to a result set
ResultSet rs = st.getResultSet();
if (rs.next())
{
String Username = rs.getString("UName");
String Password = rs.getString("PWord");
String staff = rs.getString("Staff");
String management = rs.getString("Management");
if(Username.equals(s1) & Password.equals(s2) & management.equals("Yes"))
{
JOptionPane.showMessageDialog(null, "Login Successful, Hello " + s1 );
ManagerDashboard.main(args);
signInFrame.setVisible(false);
}
if(Username.equals(s1) & Password.equals (s2) & staff.equals("Yes"))
{
JOptionPane.showMessageDialog(null, "Login Successful, Hello " + s1);
StaffDashboard.main(args);
signInFrame.setVisible(false);
}
}
else
{
JOptionPane.showMessageDialog(null, "Login Failed");
}
}
// SQL Catch block to catch errors
catch(SQLException s){
}
// Catch block to catch ActionListener errors
catch (Exception e1){
}
};
});

Collecting all rows from a database

I'm trying to retrieve all the values stored in a database where it matches the sensor name.
The code runs however, it only outputs the final value in the database.
String info = "test info"
String sensorNameStr = "test sensor name";
String sensorValueStr = "test sensor value";
String selectSQL = "select sensorvalue from sensorUsage where "+
" sensorname = '" + sensorNameStr +
"' order by TimeInserted asc";
String retrievedSensorData = "no data available";
try {
PreparedStatement pst = conn.prepareStatement(selectSQL);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
retrievedSensorData = rs.getString(1);
}
} catch (SQLException ex) {
System.out.println("Error in SQL " + ex.getMessage());
}
String json = "{\"sensor\": {\"" + sensorNameStr +
"\": \"" + retrievedSensorData + "\"}}";
System.out.println("DEBUG: json return: "+json);
Do I have to create a for loop so all values are returned and outputted on a webpage? As that's how I am viewing the data without manually going into the server. Also, if I do this, is it possible to only receive the last few inserted sensor values?
Help will be appreciated!
In your SQL query you retrieve only rows from column sensorvalue and all belong to specific sensorname. There are no other condition.
So it should be easy to make an Json with the Java EE API
// ...
JsonObject model = null;
try
{
// ...
ResultSet rs = stmt.executeQuery();
JsonArrayBuilder jsonArrayBuilder = Json.createArrayBuilder();
while(rs.next())
{
jsonArrayBuilder.add(rs.getString("sensorvalue"));
}
JsonObjectBuilder jsonObjectBuilder = Json.createObjectBuilder();
jsonObjectBuilder.add("sensorvalues", jsonArrayBuilder);
model = jsonObjectBuilder.build();
}
catch (Exception e)
{
System.out.println(e);
}
response.setContentType("application/json; charset=utf-8");
StringWriter stWriter = new StringWriter();
JsonWriter jsonWriter = Json.createWriter(stWriter);
jsonWriter.writeObject((JsonObject) model);
jsonWriter.close();
response.getWriter().append(stWriter.toString());
The output should be something like:
{"sensorvalues":["1","2"]}

View Table Names from all schema in MySql using Java

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');

Using PreparedStatement template issue

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)

DB query not populating to combo box...why?

I've been at this for awhile and have tried different examples (including a few that I found here), and tried to adapt them to what I need.
I am trying to use a DB query in a servlet to populate a combo box in the resulting html form that is created. While it all compiles and the page pops up with a combobox, there is nothing in the box to choose from, which tells me that something is wrong with how I am passing variables.
I've basically narrowed my methods down to two, but get the same results from both.
Can someone have a look-see and give me a clue?
out.print(`"<tr><td>SoldWhich Home ID: `</td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
ArrayList<String> soldWhich = new ArrayList<String>();
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String[])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
And the other method:
out.print(`"<tr><td>SoldWhich Home ID: </td><td>"`);
//Query table for results to go into option box
ResultSet rs1 = null;
Statement stmt1 = null;
Connection con1 = null;
try{
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home ORDER BY home_id";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
List<String> soldWhich = new ArrayList<String>();
while (rs1.next()){
soldWhich.add(rs1.getString(1));
}
}
catch(Exception e){}
//Begin option box
out.print(`"<select width=\"150px\" align=\"right\" name=\"soldWhichBox\">"`);
String soldWhich[] = (String [])req.getAttribute("home_id");
//populate with query output
try{
for(String sh : soldWhich){
out.print(`"<option width=\"150px\" align=\"right\" value=\""+sh+"\">"+sh+"</option>"`);
}
rs1.close();
con1.close();
}
catch (Exception e){}
out.print(`"</select>"`);
out.print(`"</td></tr>"`);
Where are you setting "home_id" request attribute and why are you even setting it? I think you should take out the following line of code and see if it works. Modify your code to this.
List<String> soldWhich = null;
try {
Class.forName(DRIVER);
con1 = DriverManager.getConnection(URL, username, password);
String sql = "SELECT home_id FROM Home";
stmt1 = con1.createStatement();
rs1 = stmt1.executeQuery(sql);
soldWhich = new ArrayList<String>();
while (rs1.next()){
for (int i=1;i<=rs1.getRow(); i++ ){
String value = rs1.getString(1);
soldWhich.add(value);
}
}
}
I think you are not actually getting values (sh) in the "for(String sh : soldWhich)" loop. Can you try printing the values in a simple table just to see if you actually get data? Also why aren't you using jstl to perform this task? And your catch block does not log any errors either in case you are actually getting some sort of errors that will go unnoticed.

Categories