Is it a good programming to pass Connection Object to a method? - jdbc

I am doing a Insert Operation , i have a condition if company is 0 , then i need to perform an additional insert in another table ??
This is my code
public static String insertIntoDepotTable(DepotJSONBean depotbean) throws SQLException
{
Connection dbConnection = null;
PreparedStatement depotjsoninsertPst = null ;
try
{
dbConnection = DBConnectionOrientDepot.getDBConnection();
dbConnection.setAutoCommit(false);
String companyId = depotbean.getCompanyId();
if(companyId.equals("0"))
{
saveInCompany(depotbean , dbConnection);
}
String Insertsql = "INSERT INTO tbl_depot values (depotID,depoBelongsToID,stateID,districtID,talukMandalID,depotName,companyID,contactName,phone1,phone2,address,latitude,longititude,accuracy,town,noOfPeopleOperating,depotSize,storageCapacity,cAndFNames,depotPic1,depotPic2,comments,active,createdOn,modifiedOn) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)";
depotjsoninsertPst = dbConnection.prepareStatement(Insertsql);
}
catch(Exception e)
{
}
} // end of method
public String saveInCompany(DepotJSONBean djsonbean , Connection conn)
{
}

Related

call an oracle function with array as parameter via hibernate

So i hava an oracle functiion like: function unbind (ids in id_table). It takes an array of ids to perform some updates on my database.
The question is how can I run my function in order to perform update operations?
What I've alreade tried:
1. Query query = getSession().createSQLQuery("call UNBIND(:ids)");
query.setParameter("ids", myIds);
query.executeUpdate();
but I got ora-06576 not a valid function or procedure name
Query query = getSession().createSQLQuery("execute UNBIND(:ids)");
query.setParameter("ids", myIds);
query.executeUpdate();
finish with ora-00900 invalid sql statement
Long [] myArray = movedIds.toArray(new Long[movedIds.size()]);
Boolean result = getSession().doReturningWork(new ReturningWork<Boolean>() {
#Override
public Boolean execute(Connection connection) throws SQLException {
CallableStatement callableStatement = connection.prepareCall("{ ? = call UNBIND(:ids)");
callableStatement.registerOutParameter(1, Types.INTEGER);
callableStatement.setArray(2, connection.createArrayOf("id_table", myArray));
callableStatement.execute();
return !(callableStatement.getInt(1) == 0);
}
});
finishes with java.sql.sqlfeaturenotsupportedexception unsupported feature
The app conects to the database via jboss, so I suppose that could be the problem in p. 3?
SELECT
UNBIND( id_table (6271789) ) FROM DUAL
does not work because my function performs updates...
Anyway is there any other method to run a function that takes an array as a parameter directly from java code?
here is a simple example, does this help?
import java.sql.*;
public class Class1 {
public static void main(String[] args) throws SQLException {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection conn = null;
try {
conn = DriverManager.getConnection(
"jdbc:oracle:thin:#//localhost/orcl","scott","tiger");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
String query = "{ ? = call test_func(?) }";
CallableStatement cs = null;
try {
cs = conn.prepareCall(query);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
int inVal = 0;
cs.setInt(2, inVal);
cs.registerOutParameter(1, oracle.jdbc.OracleTypes.NUMBER);
cs.executeUpdate();
int res = cs.getInt(1);
System.out.println("result is " + res);
}
}

Getting ambiguous result using JDBC Metadata API for Hive

I am trying to get Table names for hive using DatabaseMetaData in a similar way like RDBMS.
Sample code:
try (Connection con = getJdbcConnection(connectionUri, driverName, username, password);) {
DatabaseMetaData metadata = con.getMetaData();
ResultSet rs = metadata.getTables(null, null, tableName, null);
while (rs.next()) {
System.out.println(rs.getString(3));
}
} catch (SQLException e) {
}
private static void registerDriver(String driverName) {
try {
Class.forName(driverName);
} catch (ClassNotFoundException e) {
LOG.error("No class found for " + driverName + ". Details: " + e);
}
}
private static Connection getJdbcConnection(String connectionUri, String driverName, String username,
String password) throws SQLException{
registerDriver(driverName);
return DriverManager.getConnection(connectionUri, username,password);
}
There is no table in a particular database. Using different different table names, I am getting different output.
For example:
I put table name emp, there are 3 records with name emp
I put table name employee, there are 5 records with name employee
I put table name emp12, it is returning no records (which is expected)
Am I doing something wrong?
Shouldn't I use DatabaseMetaData for checking table existence?
I need to pass schema name in getTables method
Signature:
ResultSet getTables(String catalog,
String schemaPattern,
String tableNamePattern,
String[] types)
throws SQLException
I passed following agruments:
catalog = null;
schemaPattern = Hive schema Name
tableNamePattern = Hive Table Name
types = new String[] { "TABLE" }
Sample code:
try (Connection con = getJdbcConnection(connectionUri, driverName, username, password);) {
DatabaseMetaData metadata = con.getMetaData();
ResultSet rs = metadata.getTables(null, schemaName, tableName, new String[] { "TABLE" });
while (rs.next()) {
String tName = rs.getString("TABLE_NAME");
if (tName != null && tName.equals(tableName)) {
LOG.info("Table [" + tableName + "] is present in the Database.");
return true;
}
}
rs.close();
LOG.info("Table [" + tableName + "] is not present in the Database.");
return false;
} catch (SQLException e) {
LOG.error("Not able to get Table Metadata . Caused By: " + e);
}

ResultSet next() is returning only one row

I am having this method
public List<Course> getCourses() throws InvalidCourseDataException {
ArrayList<Course> allCoursesFromDB = new ArrayList<>();
Connection dbConnection = null;
String getFromTableSQL = "SELECT * FROM courses";
try {
dbConnection = getDBConnection();
statement = dbConnection.createStatement();
resultSet = statement.executeQuery(getFromTableSQL);
while (resultSet.next()) {
String courseCategory = resultSet.getString("course_category");
String courseTitle = resultSet.getString("course_title");
int courseId = resultSet.getInt("course_id");
Date startDate = resultSet.getTimestamp("starting_date");
Date endDate = resultSet.getDate("ending_date");
String description = resultSet.getString("description");
int teacherId = resultSet.getInt("teacher_id");
Course course = new Course(courseCategory, courseTitle, startDate, endDate);
course.setCourseId(courseId);
course.setTeacherId(teacherId);
course.setDescription(description);
addParticipantsIdToCourse(course);
allCoursesFromDB.add(course);
}
The getDBConnection() method is
private static Connection getDBConnection() {
System.out.println("-------- MySQL JDBC Connection Testing ------------");
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
My problem is that resultSet.next() is returning only the first row from DB. I'am sure that I have multiple rows. I saw JDBC ResultSet is giving only one row although there are many rows in table? that question but it really doesn't answer my :)
I am sorry for the question. I found my mistake. ResultSet next() method is working fine, but I've changed its value in my addParticipantsIdToCourse(course) method :)

How do I display arrayList contents from resultset in Java JDBC?

So I am making a simple java project to play around with JDBC in glassfish and see how it works. The program just shows you a list of surveys and a list of questions for the survey you select. However i cant seem to display the list of questions for the survey I selected. I keep getting empty values. These are the methods I have created:
convert the resultset to object model data values
public JHAKSurvey findSurvey(long id) {
System.out.println("JDBC: FIND SURVEY");
Connection connection = null;
PreparedStatement ps = null;
ResultSet rs = null;
JHAKSurvey survey = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.SURVEY WHERE ID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, id);
rs = ps.executeQuery();
while (rs.next()) {
survey = createSurveyFromResultSet(rs);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
return survey;
}
private method to query the list of questions from the QUESTION table for a survey id
private void findQuestionsBySurvey(JHAKSurvey survey){
System.out.println("JDBC: FIND QUESTIONS BY SURVEY");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.QUESTION WHERE SURVEYID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, survey.getId());
ps.executeQuery(query);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}
private method to convert the find the resultset list to an question object and add it to the survey object
private void createQuestionFromResultSet(ResultSet rs, JHAKSurvey survey){
ArrayList<JHAKQuestion> qList = new ArrayList<JHAKQuestion>();
JHAKQuestion question = new JHAKQuestion();
JHAKSurvey ss = new JHAKSurvey();
//qList.add(survey.getQuestions());
try {
while (rs.next()) {
//question.setDescription(qList.toString());
question.setId(rs.getLong("ID"));
question.setDescription(rs.getString("DESCRIPTION"));
qList.add(question);
survey.setQuestions(qList);
}
System.out.println("createQuestionFromResultSet : JDBC : successful");
} catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("createQuestionFromResultSet : JDBC : fail");
e.printStackTrace();
}
}
private method to convert a resultset to an survey object.
private JHAKSurvey createSurveyFromResultSet(ResultSet rs){
JHAKSurvey survey = new JHAKSurvey();
Boolean active = false;
String yes;
try {
yes = rs.getString("ACTIVE");
survey.setId(rs.getLong("ID"));
survey.setTitle(rs.getString("TITLE"));
if (yes.equals(Character.toString('Y'))) {
survey.setActive(true);
} else {
survey.setActive(false);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return survey;
}
What am I missing? I also seem to get error:
cannot convert from void to JHAKQuestion
When I try the method: createQuestionFromResultSet();
Thank You
Look at your method:
private void findQuestionsBySurvey(JHAKSurvey survey){
You want to get the questions of a survey, but the method returns void. Make it return a List<Question>. And in the body of the method, iterate through the resultset, transform each row into a question, add the question to a List<Question>, and return this list.
Or, if the goal of the method is to add questions to the survey passed as argument, then rename the method to
private void addQuestionsToSurvey(JHAKSurvey survey) {
and, inside the method body, call the method createQuestionFromResultSet (which should be named createQuestionsFromResultSetAndAddThemToSurvey), with the resultset and the survey as argument:
private void findQuestionsBySurvey(JHAKSurvey survey){
System.out.println("JDBC: FIND QUESTIONS BY SURVEY");
Connection connection = null;
PreparedStatement ps = null;
try {
connection = openConnection();
String query = "SELECT * FROM APP.QUESTION WHERE SURVEYID=?";
ps = connection.prepareStatement(query);
ps.setLong(1, survey.getId());
ResultSet rs = ps.executeQuery(query);
createQuestionFromResultSet(survey);
} catch (Exception e) {
e.printStackTrace();
} finally {
closeConnection(connection);
}
}

JDBC connectivity issue

I'm using the NetBeans IDE(6.8). I have a DB class :
package garits;
import java.io.Serializable;
import java.sql.*;
import java.util.Properties;
public class DB implements Serializable{
private static final long serialVersionUID = 1L;
String dbURL = "jdbc:mysql:///team_project";
String user = "root";
String pwd = "arsenal";
String dbDriver = "com.mysql.jdbc.Driver";
private Connection dbCon;
private ResultSet r;
private Statement s;
public DB()
{}
public boolean connect() throws ClassNotFoundException,SQLException{
Class.forName(dbDriver);
Properties props = new Properties();
props.put(user, "root");
props.put(pwd, "arsenal");
props.put("charSet", "UTF-8");
props.put("lc_ctype", "UTF-8");
dbCon = DriverManager.getConnection(dbURL,props);
//dbCon = DriverManager.getConnection(dbURL,user,pwd);
return true;
}
public void close() throws SQLException{
dbCon.close();
if(r!=null)
r.close();
if(s!=null)
s.close();
}
public ResultSet execSQL(String sql) throws SQLException{
s = dbCon.createStatement();
r = s.executeQuery(sql);
return (r == null) ? null : r;
}
public int updateSQL(String sql) throws SQLException{
s = dbCon.createStatement();
int r = s.executeUpdate(sql);
return (r == 0) ? 0 : r;
}
public int updateSQL(String sql, String getID) throws SQLException{
s = dbCon.createStatement();
int autoIncValue = -1;
s.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = s.getGeneratedKeys();
if (rs.next()) {
autoIncValue = rs.getInt(1);
}
return autoIncValue;
}
}
The jar file is im my library, but whenever I try to connect:
private void loginButtonActionPerformed(java.awt.event.ActionEvent evt) {
String result ="";
DB db = new DB();
try{
db.connect();
String query = "Select Role From User_Account Where Username=jTextField1.getText()AND Where Password=jTextField2.getText(); ";
ResultSet rs=db.execSQL(query);
while(rs.next())
{
result = rs.getString("Role");
}
if(result.equals(""))
{
JOptionPane.showMessageDialog(loginButton,"Access denied","Error Message",JOptionPane.ERROR_MESSAGE);
}
else if(result.equals("Administrator"))
{
MainPage_Admin admin = new MainPage_Admin();
}
}
catch(Exception e)
{
System.out.println("An error has occurred");
}
}
I get an error(the exception is caught)-the name of the database is "team_project" and password is "arsenal"-any ideas appreciated. I'm new to JDBC.
First step: use at least e.printStackTrace() in your catch-block to get some information from the exception. Otherwise you'll just be guessing.
MySQL database url connection property is wrong
jdbc:mysql://localhost:3306/<your database name>
instead of you are giving
jdbc:mysql:///team_project
modify and execute the program and better to handle the exception within the try/catch block instead of throws.

Resources