I am getting the following error when i try to execute my query(s),but i don't know why it gives me the following error every time i try to execute my query(s).The error also appears in my logcat and not in a toast as i expected.
here is my code!!
#Override
protected String doInBackground(String... strings) // Connect to the database, write query and add items to array list
{
runOnUiThread(new Runnable() {
public void run() {
try {
Connection conn = connectionClass.CONN(); //Connection Object
if (conn == null) {
success = false;
msg = "Sorry something went wrong,Please check your internet connection";
} else {
// Change below query according to your own database.
Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("yyyy/mm/dd");
String formattedDate = df.format(c);
System.out.println("it isssssssssssssssssssssssssssssssssssssssssaaaaaaaaaaaaaaaaaaaa"+getIntent().getStringExtra("nameid"));
String query = "Insert into CustomerSupportChat values('" + formattedDate + "','" + themsg.getText().toString() + "','Customer','3','"+getIntent().getStringExtra("nameid")+"','1','1') " +
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN Users_Login_Data ON " +
"CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID";
String query2 =
"Select MessageID,MessageDate,MessageText,SenderType,MessageRecieved,MessageReaded,Users_Login_Data.Username,StoresData.StoreEnglishName,StoresData.StoreArabicName FROM " +
"CustomerSupportChat INNER JOIN Users_Login_Data ON " +
"CustomerSupportChat.CustomerID = Users_Login_Data.CustomerID INNER JOIN StoresData ON " +
"CustomerSupportChat.StoreID = StoresData.StoreID Where SenderType = 'Store'";
Statement stmt = conn.createStatement();
Statement stmt2 = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSet rs2 = stmt2.executeQuery(query2);
if (rs != null) // if resultset not null, I add items to itemArraylist using class created
{
while (rs.next()) {
try {
itemArrayList.add(new ClassListChat(rs.getString("MessageDate"), rs.getString("MessageText"), rs.getString("SenderType"), rs2.getString("MessageText")));
themsg.setText("");
} catch (Exception ex) {
ex.printStackTrace();
}
}
msg = "Found";
success = true;
} else {
msg = "No Data found!";
success = false;
}
}
} catch (Exception e) {
e.printStackTrace();
Writer writer = new StringWriter();
e.printStackTrace(new PrintWriter(writer));
msg = writer.toString();
Log.d("Error", writer.toString());
success = false;
}
}
});
return msg;
}
I have tried removing while and replacing it with if statement but it showed me the same error.
I also tried my query on mssql and it executed successfully.
EDIT I solved it by changing the date format to MM/dd/yyyy.
But now i get the following error:
java.sql.SQLException: No current row in the ResultSet.
Any ideas?
Looks like there is no null check for rs2 in the below line so could throw that error:
itemArrayList.add(new ClassListChat(rs.getString("MessageDate"), rs.getString("MessageText"), rs.getString("SenderType"), rs2.getString("MessageText")));
Also a better way to check for ResultSet not returning anything is like this:
if (rs.next() == false){
msg = "No Data found!";
success = false;
} else {
do {
// add items to itemArraylist...
} while (rs.next());
}
Read more: https://javarevisited.blogspot.com/2016/10/how-to-check-if-resultset-is-empty-in-Java-JDBC.html#ixzz6KIFZZHNB
Related
I curently work on few SQL queries (MSSQL 2O14), but only "SELECT" query works with executeQuery().
I had use execute() and executeUpdate() on "INSERT INTO" and "UPDATE" queries, but whereas it looks like working, no way.
FYI, in "UPDATE_PREVIOUS_H_LOT_STATUT,
int count= p.executeUpdate(); return 1. If h_lot_number is an unknown lot number, count = 0.
So, if I use wrong data in input, my query isn't executed(Until here, I agree) but when I use the expected data, the query is executed but there is no change in my DB.
How can I find where my error is ?
UPDATE Function :
public static boolean UPDATE_PREVIOUS_H_LOT_STATUT(String h_lot_number_old) {
try {
setUpConnexion("mainDB");
String baseQuery = "UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'";
//PreparedStatement p = newTransact("UPDATE valve_assembly_h SET statut = 'Expiré' WHERE h_lot_number = '" + h_lot_number_old + "'", "mainDB");
PreparedStatement toReturn = (PreparedStatement) mainCon.prepareStatement(baseQuery);
int count = toReturn.executeUpdate();
if (count > 0) {
Log.d("Sucess : ", "Previous h_lot updated.");
closeCons();
return true;
} else {
Log.e("Error : ", "No lot found with this number.");
closeCons();
return false;
}
} catch (SQLException e) {
error = e.getMessage();
Log.e("Error :", error);
closeCons();
return false;
}
}
LOAD PREVIOUS NUMBER FUNCTION (works perfectly)
public static String LOAD_PREVIOUS_H_LOT_NUMBER(String machineNumber) {
String s = "";
try {
setUpConnexion("mainDB");
ResultSet RS = executeQuery("SELECT h_lot_number FROM valve_assembly_h WHERE machine_number = '" + machineNumber + "' AND statut = 'Actif'", "mainDB");
while (RS.next()) {
s = RS.getString(1);
Log.d("Success : ", "Lot number : " + s);
}
closeResultSet(RS);
} catch (Exception e) {
error = e.getMessage();
Log.e("Error :", error);
s = error;
}
closeCons();
return s;
}
Set up connection function : (works perfectly)
public static boolean setUpConnexion(String DBNAME) {
StrictMode.ThreadPolicy policy;
policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String connectURL;
try {
CONNECTION MS SQL SERVER
}
return true;
} catch (Exception e) {
System.out.println("SQL ERROR: " + e.getMessage());
e.printStackTrace();
return false;
}
}
Try to commit the transaction manually through the Connection object ,hope it helps.
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'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;
}
I have a problem, I cannot get my list from MS SQL Server Database.
This is my code:
public List<Location> showLocations(String nmlocation) {
List<Location> location = new ArrayList<Location>();
try {
String sql = "SELECT deskripsi FROM T_Place WHERE ID_Place='%" + nmlocation + "%'";
PreparedStatement statement = (PreparedStatement) dm.logON().prepareStatement(sql);
boolean result = statement.execute();
if (result) {
ResultSet rs = statement.getResultSet();
int i = 0;
while (rs.next())
{
Location loc = new Location(rs.getString("deskripsi"));
System.out.println(loc);
location.add(loc);
i++;
}
rs.close();
}
} catch (SQLException sqle) {
System.out.println("Error on Listing Location Data showLocation Status : " + sqle.getSQLState()
+ " \n Error Message : " + sqle.getMessage()
+ " \n Error State : " + sqle.toString());
}
return location;
}
But it shows empty resultset. How to fix it? thanks in advance.