I have my connection class like this:
public class Codb {
public static Connection connect() {
try {
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://" +
"localhost:3306/bd1";
String user = "root";
String passwd = "root";
Connection conn = (Connection) DriverManager.getConnection(url, user, passwd);
//Création d'un objet Statement
Statement state = conn.createStatement();
//L'objet ResultSet contient le résultat de la requête SQL
ResultSet result = state.executeQuery("SELECT * FROM consomateur");
//On récupère les MetaData
ResultSetMetaData resultMeta = (ResultSetMetaData) result.getMetaData();
System.out.println("\n**********************************");
//On affiche le nom des colonnes
for (int i = 1; i <= resultMeta.getColumnCount(); i++)
System.out.print("\t" + resultMeta.getColumnName(i).toUpperCase() + "\t *");
System.out.println("\n**********************************");
while (result.next()) {
for (int i = 1; i <= resultMeta.getColumnCount(); i++)
System.out.print("\t" + result.getObject(i).toString() + "\t |");
System.out.println("\n---------------------------------");
}
result.close();
/*state.close();*/
return conn;
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
The user enter the id and I want to know if the id is in the database, I created a servletin which I declared this:
static Statement St;
public ResultSet rs;
and then I have this method that verifies if the id exists or not, but it doesn't work for me.
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String req = "select id from db1.consomateur ";
try {
St = (Statement) Codb.Con.createStatement();
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
rs = (ResultSet) St.executeQuery(req);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ResultSet id = rs;
String un = request.getParameter("id");
String msg = " ";
if (un.equals(id)) {
msg = "Hello " + un + " your login is sucess";
} else {
msg = "Hello " + un + " your login is unsucess";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font siez='6' color=red>" + msg + "</font>");
}
Two ways to improve your code.
1. One simple thing, just iterate over the results in result set and check for the id that you are querying. What your are doing is, you are comparing id (referred as un your code) with result set (referred as id in your code) which is wrong. Result Set is a complex data structure which contains the sql query result data and meta data about it. Your comparison of ResultSet id with query parameter id is wrong. So one way is to iterate over the result set and compare the value of id of every row with query parameter id value and break the loop when match is found. Example: Taking over from your code
ResultSet id = rs;
String un = request.getParameter("id");
boolean flag = false;
while (id.next()) {
String i = id.getString("id");
if(un.equals(i)){
flag = true;
break;
}
}
if(flag){
msg="Hello "+ un + " your login is sucess";
}
else{
msg="Hello "+un + " your login is unsucess";
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font size='6' color=red>"+ msg+ "</font>");
So what I did is, i iterate over the result set and for each value of result set, I compared it with query parameter that u sent. If it is matched, I got a hit and I set my flag to true which mean found and I break my loop as there is no point in looking ahead. Otherwise, my loop will eventually end when all the result set entries are exhauted and nothing matches. Therefore, my flag will remain false and later I used that flag variable to set corresponding message for the case.
2. The first way is way too time consuming as the number of comparisons happening is far too much if your database contains lot of rows. On the other hand, if we modify our query a bit and use the sql where clause we can let databse handle the matching and we will enjoy the ease of programming at our end. I hope the id field in db1.consomateur is primary key, then we can use this peice of code to make our life easy.
protected void service(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
String id = request.getParameter("id");
String req = "select id from db1.consomateur where id = "+id;
boolean flag = false;
try{
Connection c = Codb.connect();
Statement st = (Statement) c.createStatement();
ResultSet rs =(ResultSet)st.executeQuery(req);
if(rs != null){
if(rs.next())
flag = true;
}
}
if(flag){
msg="Hello "+ un + " your login is sucess";
}
else{
msg="Hello "+un + " your login is unsucess";
}
catch(Exception e){
msg = e.getMessage();
}
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<font size='6' color=red>"+ msg+ "</font>");
}
So, if query get executed and we have result set not equal to null i.e. we have some data, we can check whether rs contains any rows. Since, id is a primary key, rs will contain only one row and rs.next will point to that row. Therefore, it will be our match and we have set our flag there. Otherwise flag will be false. In this case database itself take care of matching the ids and returning only the matching row to us. So, it will be faster as database create index over primary keys and we need not to create a loop which saves time.
Also, do not make Statement object static in second case as the query for each execution will be different based on id passed as parameter.
Related
I created a method to get the values from a database in java using SQL and store the information in a ResultSet and then use a while loop to store the information in a RentSendItem and store all those items in an ArrayList called sendList but when I try to run it, it gives me the error:
'ResultSet not open. Operation 'getString' not permitted. Verify that autocommit is off'
This is my class:
public void getDataFromDB() {
System.out.println("Wordk");
//connecting
Connection connection = null;
Statement statement = null;
try {
System.out.println("1");
connection = DriverManager.getConnection(url, username, password);
statement = connection.createStatement();
ResultSet name = statement.executeQuery("SELECT firstname,surname FROM CUSTOMER");
ResultSet titles = statement.executeQuery("Select Title,Category From ADDDVD ");
System.out.println(name.getString("firstname"));
System.out.println("2");
while (name.next()) {
String fullName = name.getString("firstname") + " " + name.getString("surname");
RentSendItem item = new RentSendItem(name.getString("firstname") + name.getString("surname"), titles.getString("Category"), titles.getString("title"));
sendList.add(item);
}
System.out.println("3");
} catch (Exception e) {
System.out.println("Error" + e.getMessage());
}
}
So just want to know what am I doing wrong and will this class do what I want it to do. If you could maybe help me, I would be grateful.
There are several problems in your code.
You can't call method getString() of interface java.sql.ResultSet before you call method next(). First call method next() and if that method returns "true", then you can call method getString().
You also need to call method next() on titles.
You can't call getString() twice on the same column on the same row.
Compare the below with your code.
public void getDataFromDB() {
System.out.println("Wordk");
// connecting
try (Connection connection = DriverManager.getConnection(url, username, password);
Statement statement = connection.createStatement()) {
System.out.println("1");
ResultSet name = statement.executeQuery("SELECT firstname,surname FROM CUSTOMER");
ResultSet titles = statement.executeQuery("Select Title,Category From ADDDVD ");
System.out.println("2");
while (name.next()) {
String firstname = name.getString("firstname");
String surname = name.getString("surname");
String fullName = firstname + " " + surname;
if (titles.next()) {
RentSendItem item = new RentSendItem(fullName,
titles.getString("Category"),
titles.getString("title"));
sendList.add(item);
}
}
System.out.println("3");
}
catch (Exception e) {
e.printStackTrace();
}
}
Also, the following are not problems but recommendations.
In the catch block, it usually preferable to print the entire stack trace rather than just the error message.
You should close the Connection and Statement once you no longer need them. In the code above, I have used try-with-resources
I would like to create a method that returns an array with all the values from the database.
This is what I have so far:
package ch.test.zt;
import java.sql.*;
class Database {
static boolean getData(String sql) {
// Ensure we have mariadb Driver in classpath
try {
Class.forName("org.mariadb.jdbc.Driver");
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
String url = "jdbc:mariadb://localhost:3306/zt_productions?user=root&password=test";
try {
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
return rs.next();
}
catch (SQLException e) {
e.printStackTrace();
}
return false;
}
}
That means, I could use Database.getData("SELECT * FROM users") and I get an array with all the data from the database that I need.
In my code above I am using return rs.next();, which is definitely wrong. That returns true.
rs.next(); just tell whether your result set has data in it or not i.e true or false , in order to use or create array of the actual data , you have to iterate over your result set and create a user object from it and have to add that object in your users list
Also change the signature
static List<User> getData(String sql)
And best to use like Select Username,UserId from Users; as your sql
something like this:
try { List<User> userList = new ArrayLisy();
Connection conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
//until there are results in the resultset loop over it
while (rs.next()) {
User user = new User();
user.SetName(rs.getString("username"));
// so on.. for other fields like userID ,age , gender ,loginDate,isActive etc ..
userList.add(user);
}
}
when you don't know about the columns of the table you are going to fetch then you can find the same using :
Now you know all the information then you can construct a proper query using it
and work from this
DatabaseMetaData metadata = connection.getMetaData();
ResultSet resultSet = metadata.getColumns(null, null, "users", null);
while (resultSet.next()) {
String name = resultSet.getString("COLUMN_NAME");
String type = resultSet.getString("TYPE_NAME");
int size = resultSet.getInt("COLUMN_SIZE");
System.out.println("Column name: [" + name + "]; type: [" + type + "]; size: [" + size + "]");
}
}
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'm doing the logic below using Servlet and and JSP
However if I pass the order with value, and uncomment the lines in the Servlet it works, but if the order is null, nothing happen and the exception generate a "null" message, simple as it is.
The code like is below is working, however if I uncomment the lines, it stopped if order is null. Hope I'm clear here, if not, let me know.
<td class="headerindex">Code ready date:</td>
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection connection = DbUtil.getConnection();
try {
Statement statement = connection.createStatement();
String query = "";
String order = "";
order = request.getParameter("order");
System.out.println("Order is: "+order);
//if (order.equals("code_ready_date")) {
//query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE')";
//}
//else if (order != null) {
//query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
//}
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
System.out.println("Query is: "+query);
ResultSet rs = statement.executeQuery(query);
List<Code> codes = new ArrayList<Code>();
while (rs.next()) {
Code code = new Code();
code.setEpic_project(rs.getString("epic_project"));
code.setReleases(rs.getString("releases"));
code.setJira_tickets(rs.getString("jira_tickets"));
code.setApplications(rs.getString("applications"));
code.setComponents(rs.getString("components"));
code.setCode_ready_date(rs.getString("code_ready_date"));
code.setRtb_code_deploy(rs.getString("rtb_code_deploy"));
code.setOrt_code_deploy(rs.getString("ort_code_deploy"));
code.setProd_code_deploy(rs.getString("prod_code_deploy"));
code.setProd_deploy_state(rs.getString("prod_deploy_state"));
code.setProd_launch_date(rs.getString("prod_launch_date"));
code.setDependencies(rs.getString("dependencies"));
code.setId(rs.getString("id"));
codes.add(code);
}
request.setAttribute("code", codes);
RequestDispatcher disp = request.getRequestDispatcher("ListCodes.jsp");
disp.forward(request, response);
rs.close();
statement.close();
} catch (Exception e) {
System.out.println("Exception is: " + e.getMessage());
}
}
Your getting a null pointer exception when you try and call the equals method on a null reference. When a reference is null there is no object to call the equals method on. So you need to check for null first. Try the following:
if (order == null) {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
}else if (order.equals("code_ready_date")) {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE')";
} else {
query = "SELECT * FROM codes WHERE prod_deploy_state IN ('LIVE','Dormant','...')";
}
I find that the control never seems to go in if block that starts from "if(sqlquery.equals("1"))" when it actually returns to be true. What could be the reason to it and how should ! modify it ?My program code is :
//package searchbook;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
import java.util.*;
public class SearchBook extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException,IOException{
response.setContentType("text/html");
HttpSession session = request.getSession(true);
List booklist=new ArrayList();
Connection con = null;
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\users\\ppreeti\\executive_db.accdb";
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
String user = "";
String pass = "";
String category="";
category=request.getParameter("input");
String sqlquery="select Index1.link_id "
+ "FROM Index1 "
+ " WHERE Index1.index_name LIKE '%"+category+"%' ";
try
{
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try{
Statement st = con.createStatement();
System.out.println("Connection created 1");
ResultSet rs = st.executeQuery(sqlquery);
System.out.println("Result retreived 1");
//System.out.println('"sqlquery"');
}
catch (SQLException s)
{
System.out.println("SQL statement is not executed! "+ s);
}
}
catch (Exception e){
e.printStackTrace();
}
System.out.println("************");
//String sqlq="";
if(sqlquery.equals("1"))
{
String sqlq="select Section.Section_Name , Report.Report_Name , Report.Link, Contact.Contact_Name, Metrics.Metric_Name "
+ "FROM Section , Report , Contact,Metrics "
+ "WHERE Report.Contact_ID=Contact.Contact_ID and Report.Section_ID=Section.Section_ID "
+ "and Report.Report_ID IN (SELECT Metrics.Report_ID FROM Metrics WHERE Metrics.Metric_Name = Report.Report_ID') and Metrics.Metric_Segment = 'M' ";
System.out.println("2nd query executed too !");
try
{
Class.forName(driver);
con = DriverManager.getConnection(url, user, pass);
try
{
Statement st = con.createStatement();
System.out.println("Connection created");
ResultSet rs = st.executeQuery(sqlq);
System.out.println("Result retreived ");
while (rs.next())
{
List<String> book=new ArrayList<String>();
String Name=rs.getString("Section_Name");
String reportName=rs.getString("Report_Name");
String link=rs.getString("Link");
String contactName=rs.getString("Contact_Name");
String metricName=rs.getString("Metric_Name");
//String reportId=rs.getString("Report_ID");
/*String ind_id=rs.getString("index_name");
String ind_name=rs.getString("link_id");*/
book.add(Name);
book.add(reportName);
book.add(link);
book.add(contactName);
book.add(metricName);
//book.add(reportId);
/*book.add(ind_id);
book.add(ind_name);*/
booklist.add(book);
}
}
catch (SQLException s)
{
System.out.println("SQL statement is not executed! "+ s);
}
}
catch (Exception e) {
e.printStackTrace();
}}
System.out.println("And it came here lastly !");
request.setAttribute("booklist",booklist);
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/searchbook.jsp");
dispatcher.forward(request, response);
}
}
You're setting your variable
String sqlquery="select Index1.link_id "
+ "FROM Index1 "
+ " WHERE Index1.index_name LIKE '%"+category+"%' ";
and then comparing it to 1:
if(sqlquery.equals("1"))`
which will never be true
add a String sqlResult = null; right after your sqlquery declaration
and add a sqlResult = rs.getString(1) right after your
rs = st.executeQuery(sqlquery);
then compare with sqlResult instead of sqlQuery
I suspected that you are trying to compare "string" with "int" :
if(sqlquery.equals("1"))
So it will obviously not go inside the statement.
Instead you can try this
if(sqlquery != null)
Of course it won't. sqlquery is a string containing the SQL-code ("SELECT ...").
Your string sqlquery contains a select statement so will never be equal to "1".
You need to check the result of your query, not the query string itself.
To do that, you're going to need to define rs (and the Statement as well, I believe) before the try block (so it stays in scope after that block), then evaluate it to see if it returned the data you desired.
How you do that depends on whether that "1" is meant to represent the number of rows returned or the data itself returned (from Index1.link_id).