Prepared Statement with Hibernate Session and Spring MVC - java

I have got a method with prepared statement that works with Connection class. How to make that i could work with Hibernate sessions?
#SuppressWarnings("unchecked")
#Override
public List<Users> listUsersSort(int weight, String gender, String place, int ageTo, String currentUser) {
System.out.println(weight+gender+place+ageTo+currentUser);
Connection dbConnection = null;
PreparedStatement preparedStatement = null;
int iterator=0;
List<Users> usersList =null;
String selectSQL="select users.username, users.checkusr, users.password, users.name, users.enabled, users.surname, users.email, users.gender, users.age, users.weight, users.height, users.sport, users.place, users.photo from users where users.enabled = true";
System.out.println(selectSQL);
try {
dbConnection.prepareStatement(selectSQL);
} catch (SQLException e) {
System.out.println("first catch block");
e.printStackTrace();
}
if (weight<40 == false) {
String weightParam = " AND users.weight <= ?";
selectSQL=selectSQL.concat(weightParam);
System.out.println(selectSQL);
try {
preparedStatement.setInt(iterator++, weight);
} catch (SQLException e) {
System.out.println("second catch block");
e.printStackTrace();
}
System.out.println(selectSQL);
}
if (gender.isEmpty() == false) {
String genderParam = " AND users.gender LIKE '?'";
selectSQL=selectSQL.concat(genderParam);
try {
preparedStatement.setString(iterator++, gender);
} catch (SQLException e) {
e.printStackTrace();
}
}
if (place.isEmpty() == false) {
String placeParam = " AND users.place LIKE '?'";
selectSQL=selectSQL.concat(placeParam);
try {
preparedStatement.setString(iterator++, place);
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ageTo<40 == false) {
String age = " AND users.age <= ?";
selectSQL=selectSQL.concat(age);
try {
preparedStatement.setInt(iterator++, ageTo);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
String withoutUser=" AND users.username NOT LIKE '?'";
selectSQL=selectSQL.concat(withoutUser);
try {
preparedStatement.setString(iterator++, currentUser);
} catch (SQLException e) {
e.printStackTrace();
}
System.out.println("FINAL QUERY IS: " + selectSQL);
ResultSet rs=null;
try {
rs = preparedStatement.executeQuery();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
while (rs.next()) {
String username = rs.getString("username");
System.out.println("username : " + username);
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return usersList;
}

The best way to achieve this with Hibernate is to use native queries. For example, if you're using the Session interface:
SQLQuery sqlQuery = session.createSQLQuery(selectSQL);

Related

Values not being added to database when adding a conditional if statement that should apply

I'm having a bit of problem when trying to add things to my database.
If I don't use an if statement such as this, it works:
public void onMessage(String channel, String sender, String login, String hostname, String message) {
String[] splitMessage = message.split(" ", 3);
try {
conn = TwitchBotMain.getConnection();
String query = "insert ignore into commands(name, output) values(?,?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, splitMessage[1]);
pstmt.setString(2, splitMessage[2]);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
However, if I add this if statement to the mix, it doesn't log anything to the database:
public void onMessage(String channel, String sender, String login, String hostname, String message) {
String[] splitMessage = message.split(" ", 3);
if (splitMessage[0] == "!add") {
try {
conn = TwitchBotMain.getConnection();
String query = "insert ignore into commands(name, output) values(?,?)";
pstmt = conn.prepareStatement(query);
pstmt.setString(1, splitMessage[1]);
pstmt.setString(2, splitMessage[2]);
pstmt.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
pstmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Eclipse isn't showing any Java errors.
Always use equals() instead of == when compare string:
if (splitMessage[0].equals("!add"))
try:
if (splitMessage[0].equals("!add")) {
with == you compare the reference not the values of your strings.

insert single data in data base but in data base duplicate row also added at time of insertion

I would like to insert single data in data base at a time but in data base duplicate row generate at a time.
-----------------------------
Output(in mysql table=privilege)
-----------------------------
id privilege
1 abc
2 abc
Here's how I insert the data:
public int addPrivilege(String privilege) {
PreparedStatement preparedStatement = null;
String sqlprivilege;
Connection dbConnection = null;
int pinsert = 0;
try {
sqlprivilege = "insert into privilege(privilege) values(?)";
dbConnection = ConnectionDao.getDBConnection();
preparedStatement = dbConnection.prepareStatement(sqlprivilege);
preparedStatement.setString(1, privilege);
pinsert = preparedStatement.executeUpdate();
if(preparedStatement.executeUpdate()==1)
pinsert=1;
else
pinsert=0;
System.out.println("privilege is add and name is:- " +privilege);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pinsert;
}
You execute the sql twice in your code.
1) pinsert = preparedStatement.executeUpdate();
2) if(preparedStatement.executeUpdate()==1)
I'm not sure about the return values of the executeUpdate. But i think the first is enough, no need to check for the return values. If you need to then compare with pinsert instead of executeupdate (again).
if(pinsert == 1)
You are using two time executeUpdate(); delete execute which one is in if case
public int addPrivilege(String privilege) {
PreparedStatement preparedStatement = null;
String sqlprivilege;
Connection dbConnection = null;
int pinsert = 0;
try {
sqlprivilege = "insert into privilege(privilege) values(?)";
dbConnection = ConnectionDao.getDBConnection();
preparedStatement = dbConnection.prepareStatement(sqlprivilege);
preparedStatement.setString(1, privilege);
pinsert = preparedStatement.executeUpdate();
//try this
if(pinsert ==1)
pinsert=1;
else
pinsert=0;
System.out.println("privilege is add and name is:- " +privilege);
} catch (SQLException e) {
System.out.println(e.getMessage());
} finally {
if (preparedStatement != null) {
try {
preparedStatement.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (dbConnection != null) {
try {
dbConnection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
return pinsert;
}

"Operation not allowed after ResultSet closed" with Datasource and crawler4j

After reading through a lot of similar questions I have not been able to get a solution that works for me.
I have this methods:
In a crawler4j Controller I do this:
ArrayList<String> urls = Urls.getURLs(100);
for (String s : urls) {
System.out.println("Adding URL: " + s);
controller.addSeed(s);
}
this is getURLs():
public static ArrayList<String> getURLs(int number) {
ArrayList<String> list = new ArrayList<String>();
String getStatement = "select * from " + Configurations.getStringProperty("mysql.urls.db_name", "urls") + " where retrieved=0 limit "
+ Configurations.getStringProperty("mysql.urls.limit", "100") + ";";
ResultSet rs;
rs = Databaseclient.executeStatement(getStatement);
try {
while (rs.next()) {
list.add(rs.getString("url"));
// Databaseclient.executeStatement("update urls set retrieved = true where id = "
// + rs.getInt("id") + ";");
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return list;
}
This is my executeStatement():
public static ResultSet executeStatement(String s) {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
// fetch a connection
connection = DataSource.getInstance().getConnection();
if (connection != null) {
statement = connection.createStatement();
resultSet = statement.executeQuery(s);
}
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
} catch (IOException e) {
System.out.println("A IOException occured executing the Statement");
e.printStackTrace();
} catch (PropertyVetoException e) {
System.out.println("A PropertyVetoException occured executing the Statement");
e.printStackTrace();
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
}
}
}
return resultSet;
}
I get the error
java.sql.SQLException: Operation not allowed after ResultSet closed
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1094)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:997)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:983)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:928)
at com.mysql.jdbc.ResultSetImpl.checkClosed(ResultSetImpl.java:799)
at com.mysql.jdbc.ResultSetImpl.next(ResultSetImpl.java:6982)
at database.Urls.getURLs(Urls.java:27)
at crawler.Controller.main(Controller.java:53)
Which is the line
while (rs.next()) {
in my getURLs() method.
What am I doing wrong? There is no code between getting the statement and the while loop that could close the statement.
Your code is a bit off, but if I understand you then don't close your ResultSet in the finally block of your executeStatement method.
public static ResultSet executeStatement(Connection connection,
Statement statement, String s) {
ResultSet resultSet = null;
try {
if (statement != null) {
resultSet = statement.executeQuery(s);
}
} catch (SQLException e) {
System.out.println("A SQLException occured executing the Statement");
e.printStackTrace();
} catch (IOException e) {
System.out.println("A IOException occured executing the Statement");
e.printStackTrace();
} catch (PropertyVetoException e) {
System.out.println("A PropertyVetoException occured executing the Statement");
e.printStackTrace();
}
return resultSet;
}
Then you need to pass in a Connection and Statement, and you'll get a ResultSet back. Also, the caller should then close all three when it's done with the ResultSet.

JComboBox as search field

I refer this first and edited like this..same combobox name.but when I call this method it ask for a keyEvent..for that what should I do.and is there any wrong with this code
ResultSet rset;
public void srKeyTyped(java.awt.event.KeyEvent evt){
String sch = ((JTextField)ComboItemName.getEditor().getEditorComponent()).getText();
try {
rset = new JDBC.DB().getData("SELECT * FROM item_reg WHERE id = '"+sch+"'");
} catch (Exception e) {
System.out.println(e);
}
ComboItemName.removeAllItems();
try {
while (rset.next()) {
String item = rset.getString("id");
ComboItemName.addItem(item);
}
} catch (SQLException ex) {
System.out.println(ex);
//Logger.getLogger(dataprocess.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println(sch);
ComboItemName.setSelectedItem(null);
ComboItemName.setPopupVisible(true);
((JTextField)ComboItemName.getEditor().getEditorComponent()).setText(sch);
}

can't get connection to database through java class

i'm trying to establish connection with mysql database through file properties and then run the information from servlet. my Connection class looks like this:
public class pageDao {
private Connection connection;
private Statement statement;
private pageDao() {
Properties prop = new Properties();
try {
//Class.forName("oracle.jdbc.driver.OracleDriver");
//Class.forName("org.gjt.mm.mysql.Driver");
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException cnfe) {
System.out.println("Error loading driver: " +cnfe);
}
try {
try {
//load a properties file
prop.load(new FileInputStream("config.properties"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String db = prop.getProperty("database");
String dbuser = prop.getProperty("dbuser");
String dbpassword = prop.getProperty("dbpassword");
connection = DriverManager.getConnection(db,dbuser,dbpassword);
} catch (SQLException e) {
e.printStackTrace();
}
}
private static pageDao thisDao;
public static pageDao gedDao()
{
if(thisDao == null)
thisDao = new pageDao();
return thisDao;
}
public PageData getPage(String id)
{
PageData data = new PageData();
try {
statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from pages where id='"+id+"'");
if(rs.next())
{
data.setId(rs.getString("id"));
data.setParentid(rs.getString("parentid"));
data.setTitle(rs.getString("title"));
data.setTitle4menu(rs.getString("title4menu"));
data.setKeywords(rs.getString("keywords"));
data.setDescription(rs.getString("description"));
data.setMaintext(rs.getString("maintext"));
}
else
return null;
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return data;
}
when i run it, it doesn't show the mistake that connection wasn't established, but when it gets to the
public PageData getPage(String id) {
PageData data = new PageData();
try {
statement = connection.createStatement();
it throws java.lang.NullPointerException.
can anybody help me out with that?
there is no issue with code.
check your passing parameter ...
check sample
private Connection getConnection() {
try {
String dbUrl = "jdbc:mysql://localhost:3306/projectmining";
Class.forName("com.mysql.jdbc.Driver");
return DriverManager.getConnection(dbUrl, "root", "admin");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}

Categories