I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}
Related
My complete code to access data from two different databases using single hive jdbc driver. I get sql exception on next database connection, before that it works perfectly. Kindly, suggest me some solution to further process. Where as next prepared statement query throws sql exception. But doing on a separate button action it works fine, while i'm doing in a single action it throws error.
String s1 = jTextField1.getText();
String s2 = jTextField2.getText();
String s3 = jTextField3.getText();
String s4 = new String(jPasswordField1.getPassword());
try {
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/twitter_db", "arunachalam", "");
Statement st = con.createStatement();
String sql = "select dbname,tbname from check where userid='" + s3 + "'and tbname='" + s2 + "'";
String sql1 = "select userid,password from user_reg where userid='" + s3 + "'";
ResultSet rs = st.executeQuery(sql);
try {
PreparedStatement ps = con.prepareStatement(sql1);
ResultSet rs1 = ps.executeQuery();
while (rs.next() && rs1.next()) {
if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
jSeparator1.setVisible(true);
jScrollPane1.setVisible(true);
try {
Connection con1 = DriverManager.getConnection("jdbc:hive2://localhost:10000/" + s1, "arunachalam", "");
ArrayList<Tweet> list = new ArrayList<Tweet>();
String ve = "select id,created_at,source,favorited,retweet_count,retweeted_status,entities,text,user,in_reply_to_screen_name from " + s2;
PreparedStatement ps1 = con1.prepareStatement(ve);
ResultSet rs2 = ps1.executeQuery();
Tweet tweet;
while (rs2.next()) {
tweet = new Tweet(rs.getLong("id"), rs.getString("created_at"), rs.getString("source"), rs.getBoolean("favorited"), rs.getInt("retweet_count"), rs.getString("retweeted_status"), rs.getString("entities"), rs.getString("text"), rs.getString("user"), rs.getString("in_reply_to_screen_name"));
list.add(tweet);
String[] columnName = {"Tweet_ID", "Created_At", "Source", "Favorited", "Retweet_Count", "Retweeted_Status", "Entities", "Text", "User", "Screen_Name"};
Object[][] twt = new Object[list.size()][10];
for (int i = 0; i < list.size(); i++) {
twt[i][0] = list.get(i).gettweetid();
twt[i][1] = list.get(i).getcreated();
twt[i][2] = list.get(i).getsource();
twt[i][3] = list.get(i).getfavor();
twt[i][4] = list.get(i).getcount();
twt[i][5] = list.get(i).getstatus();
twt[i][6] = list.get(i).getentities();
twt[i][7] = list.get(i).gettext();
twt[i][8] = list.get(i).getuser();
twt[i][9] = list.get(i).getscreen();
TheModel model = new TheModel(twt, columnName);
jTable1.setModel(model);
jTable1.setRowHeight(20);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
break;
} else if ((!rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Database Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (!rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Table Name is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("userid").equals(s3)) && (!rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "Password is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else if ((!rs1.getString("userid").equals(s3)) && (rs.getString("dbname").equals(s1)) && (rs.getString("tbname").equals(s2)) && (rs1.getString("password").equals(s4))) {
JOptionPane.showMessageDialog(null, "User ID is Incorrect", "Error", JOptionPane.ERROR_MESSAGE);
break;
} else {
JOptionPane.showMessageDialog(null, "Access Denied", "Error", JOptionPane.ERROR_MESSAGE);
}
}
} catch (Exception e) {
showMessageDialog(null, e);
}
} catch (Exception e) {
showMessageDialog(null, e);
}
To be responsive, as the application would freeze during actionPerformed use
invokeLater.
Yes separate connections for instance with different users, one for reading only, one for admin tasks, is quite possible. However I did not see calls to close().
(Also a single-user (such as an embedded) database might not do.)
To automatically close connection, statement and result set use try-with-resources: try (DECLARATION; ... ; DECLARATION) { ... } - saves a lot.
The explicit class loading with Class.forName no longer is needed for current drivers.
// Java 8
SwingUtilities.invokeLater(() -> {
String sql = "select dbname, tbname from check where userid=? and tbname=?";
try (Connection con = DriverManager.getConnection(
"jdbc:hive2://192.168.1.13:10000/twitter_db", "arunachalam", "");
PreparedStatement st = con.prepareStatement(sql)) {
st.setString(1, s3);
st.setString(2, s2);
try (ResultSet rs = st.executeQuery()) {
if (rs.next()) {
List<Tweet> list = new ArrayList<>();
String hive = "select id,created_at,source,favorited,retweet_count,"
+ "retweeted_status,entities,text,user,in_reply_to_screen_name from "
+ s2;
try (Connection con1 = DriverManager.getConnection(
"jdbc:hive2://localhost:10000/"+s1, "arunachalam", "");
PreparedStatement ps1 = con1.prepareStatement(hive);
ResultSet rs2 = ps1.executeQuery()) {
...
});
i have built quiz web project.
i want to insert below mentioned test question into database. i am writing this question in html textarea, then getdata from html with inner.html :
but when i select this question from database it looks like that, it is hard readable, carelessly written:
help me make above mentioned tests readable.
my sql insert code :
public void addtest(TestModel test) throws Exception {
Connection c = null;
PreparedStatement ps = null;
String sql = "INSERT INTO TEST_TABLE (QUESTION,A,B,C,D,E,QUESTION_TYPE,SCORE,SUBJECT, CORRECT, Variant) " +
" VALUES (?,?,?,?,?,?,?,?,?,?,?) ";
try {
c= DbHelper.getConnection();
if(c != null) {
ps = c.prepareStatement(sql);
ps.setString(1,test.getQuestion());
ps.setString(2,test.getOptionA());
ps.setString(3,test.getOptionB());
ps.setString(4,test.getOptionC());
ps.setString(5,test.getOptionD());
ps.setString(6,test.getOptionE());
ps.setString(7,test.getQuestionType());
ps.setLong(8,test.getScore());
ps.setLong(9,test.getSubjectId());
ps.setString(10,test.getCorrectOption());
ps.setInt(11,test.getVariant());
ps.execute();
} else {
System.out.println("Connection is null");
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtility.close(c,ps,null);
}
}
my sql select code :
public TestModel getquestionlist(long firstpage,int variant) throws Exception {
TestModel testdata = new TestModel();
Connection c = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql =" SELECT TE.ID,TE.QUESTION,TE.A,TE.B,TE.C,TE.D,TE.E,TE.F,TE.G,TE.QUESTION_TYPE,TE.SCORE,S.NAME as Subject,TE.CREATE_DAY,TE.CORRECT, d.value, TE.Variant FROM TEST_TABLE TE " +
"INNER JOIN SUBJECT S ON S.ID = TE.SUBJECT " +
"inner join dictionary d on d.ID = TE.Variant " +
"WHERE TE.ACTIVE =1 AND S.ACTIVE =1 AND TE.Variant = ? " +
"LIMIT ?,1; ";
try {
c = DbHelper.getConnection();
if (c != null) {
ps = c.prepareStatement(sql);
ps.setInt(1,variant);
ps.setLong(2, firstpage);
rs = ps.executeQuery();
while (rs.next()) {
testdata.setId(rs.getLong("ID"));
testdata.setQuestion(rs.getString("QUESTION"));
testdata.setOptionA(rs.getString("A"));
testdata.setOptionB(rs.getString("B"));
testdata.setOptionC(rs.getString("C"));
testdata.setOptionD(rs.getString("D"));
testdata.setOptionE(rs.getString("E"));
testdata.setOptionF(rs.getString("F"));
testdata.setOptionG(rs.getString("G"));
testdata.setQuestionType(rs.getString("QUESTION_TYPE"));
testdata.setScore(rs.getLong("SCORE"));
testdata.setTestSubject(rs.getString("Subject"));
testdata.setCreateDate(rs.getDate("CREATE_DAY"));
testdata.setCorrectOption(rs.getString("CORRECT"));
testdata.setVariant(rs.getInt("Variant"));
}
}
} catch (Exception ex) {
ex.printStackTrace();
} finally {
JdbcUtility.close(c, ps, rs);
}
return testdata;
}
You can use <br/> to break line :
"1: public class WaterBottle { <br/>"
So in the moment of getting the result you can concatenate your result with <br/> for example :
testdata.setQuestion(rs.getString("QUESTION") + "<br/>");
I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html
This question already has answers here:
Passing table name as parameter of prepared statement [duplicate]
(3 answers)
Closed 6 years ago.
public List<User> arrangeUsers(String option) {
String query = "";
if (option.equals("lastNameAsc")) {
query = "SELECT * FROM ? ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query = "SELECT * FROM ? ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
if (searchList.size() > 0) {
stmt.setString(1, "search_results");
searchList.clear();
listChoice = true;
} else {
stmt.setString(1, "users");
users.clear();
listChoice = false;
}
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
The above method returns an error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near ''users' ORDER BY lastName DESC' at line 1 " error.
The method is supposed to arrange a list of users (a table) according to the order required by the client. Any suggestions what is the reason for the error message? I am ready to provide any additional details if necessary.
A table name can't be used as a parameter. It must be hardcoded. You can do something like:
public List<User> arrangeUsers(String option) {
String query = "SELECT * FROM ";
if (searchList.size() > 0) {
query += "search_results ";
searchList.clear();
listChoice = true;
} else {
query += "users ";
users.clear();
listChoice = false;
}
if (option.equals("lastNameAsc")) {
query += "ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query += "ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query += "ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query += "ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
Hope it helps.
Every time I run this code it gives me an exhauset resultset error. Im not sure what Im doing wrong but Ive tried removing the .next(); code for either one or all resultsets and then the error given is the ResultSet next wasnt called.
Im not sure what Im doing wrong. Just curious what people might think the issue could be? Ive done similar earlier in my servlet code but only used 1 statement and then 1 prepared statement. This time Im using 2 statements and 1 prepared statement.
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
rs11.next();
ResultSet rs12 = stmt.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
rs12.next();
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
int olo1 = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
PreparedStatement pstmt1 = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)");
pstmt1.clearParameters();
pstmt1.setInt(1,olo);
pstmt1.setInt(2,olo1);
ResultSet rs1 = pstmt1.executeQuery();
rs1.next();
Some ideas on your code (in comments)
stmt = con.createStatement();
stmt1 = con.createStatement();
ResultSet rs11 = stmt.executeQuery("SELECT recipe_ID FROM GM_Recipes WHERE rec_name='" + op1 + "'"); //choose recipe_ID from sql table
//Check if you HAVE a line here!
if(!rs11.next()) {
System.out.println("No Recipe Found");
}
//Use stmt1 - that's why you created it?!
ResultSet rs12 = stmt1.executeQuery("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name='" + ingr1 + "'"); //choose ingredient_ID from sql table
if(!rs12.next()) {
System.out.println("No Ingredient Found");
}
int olo = ((Number) rs11.getObject(1).intValue(); //convert resultset value to int
//Read Ingredient from rs12 -> that's where you selected it into
int olo1 = ((Number) rs12.getObject(1).intValue(); //convert resultset value to int
While this might point you into the right direction for solving the current issue, you should consider learning about clean code.
Consider this code making use of try-with-resource, refactored out some methods, using prepared statements.
//Replace exiting code
String opt1 = req.getParameter("RecName"); //Retrieves info from HTML form
String ingr1 = req.getParameter("Ing1"); //Retrieves info from HTML form
int recipieId = getRecipeId(con, opt1);
int ingredientId = getIngredientId(con, ingr1);
if(recipeId > 0 && ingredientId > 0) {
//Process result
insertRecLnk(con, recipeId, ingredientId);
} else {
System.out.println("No INSERT");
}
//Helper functions
protected int getRecipeId(Connection con, String rec) {
try(PreparedStatement st = con.prepareStatement("SELECT recipe_ID FROM GM_Recipes WHERE rec_name=?")) {
st.setString(1, rec);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Recipe Found");
return -1;
}
protected int getIngredientId(Connection con, String ing) {
try(PreparedStatement st = con.prepareStatement("SELECT ingredient_ID FROM GM_IngredientDB WHERE ing_name=?")) {
st.setString(1, ing);
try(ResultSet rs11 = st.executeQuery()) {
//choose recipe_ID from sql table
if(rs11.next()) {
return rs11.getInt(1);
}
}
} catch(SQLException e) {
e.printStackTrace();
}
System.out.println("No Ingredient Found");
return -1;
}
protected void insertRecLnk(Connection con, int rId, int iId) {
try(PreparedStatement ps = con.prepareStatement("INSERT INTO GM_RecLnk(recipe_ID,ingredient_ID) VALUES (?,?)")) {
ps.setInt(1, rId);
ps.setInt(2, iId);
ps.executeUpdate();
} catch(SQLException e) {
e.printStackTrace();
}
}