JTable has size limitations? - java

the table only displays 3083 line while in mysql are more than that !
DefaultTableModel modelEtud = new DefaultTableModel(null, new String[]{"N°", "C.I.N. / N° inscription", "Nom Fr", "Prenon Fr", "Matière", "Nombre Absences", "Groupe"}) {
};
String requetEtud = "SELECT * FROM etudiant2sga WHERE id = '" + resultatAbs.getString("idEtudiant") + "' AND idGroupe = '" + idGroupe + "' LIMIT 0 , 10000";
try {
ResultSet resultat = stmtSelectEtudiant.executeQuery(requetEtud);
while (resultat.next()) {
modelEtud.addRow(new Object[]{N, resultat.getString("id"), resultat.getString("nomFr"), resultat.getString("prenomFr"), EE, new SimpleDateFormat("dd-MM-yyyy").format(resultatAbs.getDate("dateAbs")), "séance " + resultatAbs.getInt("seance"), jTableGpr.getValueAt(row, 2)});
}
}
even with this code the problem is not solved:
modelEtud.setRowCount(10000);

Related

error insert data in java netbeans and mysql

I am a beginner in learning programming and I am trying to apply what I learned with an application example in java , and I encountered a problem. I hope you will find a solution, please.
When I insert data the combobox (combo_produits) it doesn't give me the specified value,
The code has no errors, but the combobox does not give us the desired value despite using the function getSelectedIndex() .
/*method of combobox combo_produits */
private void combo_PRODUIT() {
try {
String qyP = "SELECT CONCAT(NOM_COM,' ',lib_court,' ',DOSAGE ,' ',UNITE , ' ', CONDIT)AS DESIGNATION "
+ "FROM produit JOIN forme USING(cd_forme) ";
prs_sort = connectio.prepareStatement(qyP);
rs_sort = prs_sort.executeQuery();
while (rs_sort.next()) {
combo_produits.addItem(rs_sort.getString("DESIGNATION"));
}
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
}
/* button of insert */
private void valider_bpActionPerformed(java.awt.event.ActionEvent evt) {
int pharID = 0;
int donid = 0;
int lotID = 0;
int prodid= 0 ;
try {
String qr1 = "insert into tbl_pharmacien (NOM_PHARM) values ('" + combo_pharm.getSelectedItem() + "')";
prs_sort = connectio.prepareStatement(qr1, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
pharID = rs_sort.getInt(1);
}
String qr2 = "insert into donner_medic (PHARM_ID , DATE_ECHANDONN) values "
+ "('" + pharID + "', '" + new SimpleDateFormat("yyyy-MM-dd").format(date_prod_sort.getDate()) + "' )";
prs_sort = connectio.prepareStatement(qr2, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
donid = rs_sort.getInt(1);
}
int index =combo_produits.getSelectedIndex();
String qr3 = " insert into tbl_lot (NUM_ENR,PPA, QNT) values "
+ "('" +index + "', '" + txtf_ppa.getText() + "', '" + txt_Qnt.getText() + "' )";
prs_sort = connectio.prepareStatement(qr3, prs_sort.RETURN_GENERATED_KEYS);
prs_sort.executeUpdate();
rs_sort = prs_sort.getGeneratedKeys();
while (rs_sort.next()) {
lotID = rs_sort.getInt(1);
}
String qr4 = "insert into tbl_donnelot (LOT_ID,DONN_ID) values ('" + lotID + "', '" + donid + "')";
prs_sort = connectio.prepareStatement(qr4);
prs_sort.executeUpdate();
} catch (Exception exp) {
JOptionPane.showMessageDialog(null, exp.getMessage());
}
Table_prod_sort();
}
For example let's create a compobox with the student's name:
First, we work a class with the student's name and id for him, and we do the Setter, getter and Constructor functions.
Second, we create a function to link the database with the students' class, thus:
public class class_array {
private Connection co=get_connection.ConnDb() ;
private PreparedStatement prst ;
private ResultSet res ;
public HashMap<String, Integer> fillCombobox(){
String sqls = "SELECT `ID_student`, `Name_student` FROM `student`";
HashMap<String, Integer> hmp = new HashMap<String, Integer>();
try {
prst = co.prepareStatement(sqls);
res = prst.executeQuery();
student st ;
while(res.next()){
st = new student(res.getInt(1), res.getString(2));
hmp.put(st.getName_stud(), st.getId_stu());
}
} catch (SQLException ex) {
Logger.getLogger(student_f.class.getName()).log(Level.SEVERE, null, ex);
}
return hmp ;
}}
Third, in the form we write the compobox content display function like this :
private void combo(){
class_array std = new class_array();
HashMap<String, Integer> hmp = std.fillCombobox();
for (String cb :hmp.keySet()) {
combo_st.addItem(cb);
}
}
And finally, like in the previous example, we want to use the last Selection of combobox , so we write the following:
private void bp_valid_indexActionPerformed(java.awt.event.ActionEvent evt) {
class_array stb = new class_array();
HashMap<String,Integer> has = stb.fillCombobox();
int index = has.get(combo_st.getSelectedItem().toString()).toString();
}
I found the solution, and it lies in displaying the content of the combobox with linking it to the number of his id, so that when we work getSelectedItem the value of the combobox is selected with his id

How to get data from an ArrayList <List> in another class?

I'm using RecyclerView I have an Activity that queries my database and I insert this data into that ArrayList , and I want to list that data in another Activity.
This is where I query and add the data to the ArrayList
String queryProduto = "SELECT" +
" Produto_Servico.ID, Produto_Servico.Descricao," +
" Produto_Estoque.EstoqueAtual, ValorVenda" +
" FROM" +
" Produto_Valor" +
" INNER JOIN" +
" Produto_Servico" +
" ON" +
" Produto_Servico.ID = Produto_Valor.ID_Produto" +
" INNER JOIN" +
" Produto_Estoque" +
" ON" +
" Produto_Estoque.ID_Produto = Produto_Servico.ID" +
" WHERE" +
" Produto_Estoque.EstoqueAtual > 0" +
" ORDER BY" +
" Produto_Servico.Descricao";
Statement stmtP = connect.createStatement();
ResultSet rsP = stmtP.executeQuery(queryProduto);
String queryPessoa = "SELECT ID_Pessoa FROM Novo_Pedido";
Statement stmtPS = connect.createStatement();
ResultSet rsPS = stmtPS.executeQuery(queryPessoa);
while (rsPS.next()){
cod = rsPS.getString("ID_Pessoa");
}
if (rsP != null) {
while (rsP.next()) {
id = String.valueOf(rsP.getString("ID"));
desc = rsP.getString("Descricao");
estoque = String.valueOf(rsP.getString("EstoqueAtual"));
valorDec = rsP.getBigDecimal(4);
qtdStr = String.valueOf(qtd);
valorStr = decimalFormat.format(valorDec);
String descFinal = desc;
String qtdFinal = qtdStr;
final BigDecimal[] valorFinal = {valorDec};
try {
listProdutosPedidosFinalizar.add(new ListProdutosPedidosFinalizar(descFinal, qtdFinal, valorFinal[0], BigDecimal.ZERO));
classeLists.setListProdutosPedidosFinalizar(listProdutosPedidosFinalizar);
produtosPedidosAdapter = new ProdutosPedidosAdapter(listProdutosPedidos, this, new ProdutosPedidosAdapter.OnClickListener() {
/*METHODS*/
produtosPedidosAdapter.notifyDataSetChanged();
listProdutosPedidos.add(new ListProdutosPedidos(id, desc, estoque, valorStr, qtdStr));
} catch (Exception ex) {
ex.printStackTrace();
}
rvProdutosPedidos.setAdapter(produtosPedidosAdapter);
produtosPedidosAdapter.notifyDataSetChanged();
isSuccess = true;
}
And now I want to list the listProdutosPedidos data in another Activity.
Define listProdutosPedidos list as static member of your class and then use className.listProdutosPedidos code to access records in it.

How to Load "result set" one by one into table view?

I have loaded millions of rows of data from 5 tables in database. I want to display the loaded data into a tableview. It takes a long time to load all the records(sometimes all of them don't fit into memory). I want to make it so that I can load a resultSet, display it, load a second one, and so on. Is this possible? My code as of now:
#FXML
private TableView<Vysledok_hladania> table;
#FXML
private TableColumn<Vysledok_hladania, String> Nazov_hotela, Adresa, Krajina, Mesto, Hviezdicky, Cena, Typ_izby, Pocet_izieb;
#FXML
void vyhladajInfo(ActionEvent event){
table.getItems().clear();
try {
Connection con = Runner.getConnection();
con.setAutoCommit(false);
String query = "SELECT h.\"Nazov hotela\", k.\"Nazov krajiny\", m.\"Nazov mesta\", h.\"Adresa hotela\", h.\"Hviezdicky\", p.\"Cena pobytu\", i.\"Typ izby\", h.\"Pocet izieb\" FROM hotel h " +
"inner JOIN izba i ON i.\"ID hotela\" = h.\"ID hotela\" " +
"inner JOIN krajina k ON k.\"ID krajiny\" = h.\"ID krajiny\" " +
"inner JOIN mesto m ON m.\"ID mesta\" = h.\"ID mesta\" " +
"inner JOIN pobyt p ON p.\"ID hotela\" = h.\"ID hotela\" " +
"WHERE h.\"Nazov hotela\" = ? " +
"AND k.\"Nazov krajiny\" = ? " +
"AND h.\"Hviezdicky\" = ? " +
"AND i.\"Pocet posteli\" >= ? " +
"AND p.\"Cena pobytu\" <= ? ";
//"AND p.\"Datum od\" = ? " +
//"AND p.\"Datum do\" <= ?";
int i = 1;
PreparedStatement pst = con.prepareStatement(query, ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
pst.setFetchSize(50);
pst.setString(1,Text_nazov.getText());
pst.setString(2,(String)krajina.getValue());
int pocet_hviezdiciek = Integer.parseInt((String)hviezdicky.getValue());
pst.setInt(3,pocet_hviezdiciek);
int pocet_osob = Integer.parseInt((String)osoby.getValue());
pst.setInt(4, pocet_osob);
double cena_pobytu = Double.parseDouble(Text_cena.getText());
pst.setDouble(5, cena_pobytu);
// Date datum_OD = Date.valueOf(date_od.getValue());
// pst.setDate(6, datum_OD);
// Date datum_DO = Date.valueOf(date_do.getValue());
// pst.setDate(7, datum_DO);
ResultSet rs = pst.executeQuery();
System.out.println(pst);
Nazov_hotela.setCellValueFactory(new PropertyValueFactory<>("Meno_hotela"));
Krajina.setCellValueFactory(new PropertyValueFactory<>("Krajina"));
Mesto.setCellValueFactory(new PropertyValueFactory<>("Mesto"));
Adresa.setCellValueFactory(new PropertyValueFactory<>("Adresa"));
Hviezdicky.setCellValueFactory(new PropertyValueFactory<>("Hviezdicky"));
Cena.setCellValueFactory(new PropertyValueFactory<>("Cena"));
Typ_izby.setCellValueFactory(new PropertyValueFactory<>("Typ_izby"));
Pocet_izieb.setCellValueFactory(new PropertyValueFactory<>("Pocet_izieb"));
while(rs.next()){
oblist.add(new Vysledok_hladania(rs.getString("Nazov hotela"),
rs.getString("Nazov krajiny"),
rs.getString("Nazov mesta"),
rs.getString("Adresa hotela"),
rs.getInt("Hviezdicky"),
rs.getDouble("Cena pobytu"),
rs.getString("Typ izby"),
rs.getInt("Pocet izieb")));
System.out.println(i++);
}
rs.close();
pst.close();
con.close();
} catch(SQLException ex){
Logger.getLogger(Result_Controller.class.getName()).log(Level.SEVERE, null, ex);
}
table.setItems(oblist);
}

How to check if id is exists in Android?

I want to check if id is exists in SQLIte DB then update that id , if id is not present in SQLite then insert that id. How can i do this. Can someone help how to work with.Thanks to Appreciate.
Here is my Activity code
public void saveResult()
{
AnswerOptions = (RadioButton) findViewById(Options_RadioGroup.getCheckedRadioButtonId());
String str_AnswerOptions = AnswerOptions.getText().toString().trim();
System.out.println("rbVal = " + str_AnswerOptions);
if (str_AnswerOptions.equals(((Datastructure) Vectore_mquestionDatabaseStructure .get(StaticClass.QuestionNumber)).Answer))
{
if (!StaticClass.isTest)
{
try
{
DatabaseHelper databaseHelper = new DatabaseHelper(this.getApplicationContext());
sqdb = databaseHelper.getWritableDatabase();
String strCountQuery = "SELECT question_id, question_type , question_no FROM question_answers where question_id = " + convertVector ;
Cursor cur = sqdb.rawQuery(strCountQuery , null);
if (cur.moveToFirst())
{
int iCount = cur.getCount();
System.out.println("iCount = " + iCount);
if(cur.getCount() <= 0 )
{
String strstrqueType = txtViewQuestiontype.getText().toString().trim();
String str_que = txtViewQuestion.getText().toString().trim();
String str_marks = "1";
databaseHelper.insertQueDetails(strQueLimit, strstrqueType, str_que, str_AnswerOptions, str_marks , strOption_Id);
System.out.println("strQueLimit = " + strQueLimit + ", strstrqueType = " + strstrqueType +" , str_que = " + str_que + " , str_AnswerOptions = " + str_AnswerOptions + ", str_marks = " + str_marks + ", strOption_Id = " + strOption_Id);
Toast.makeText(this, " Right Answer ", Toast.LENGTH_LONG).show();
}
else
{
cur.moveToFirst();
qid = cur.getInt(cur.getColumnIndex("question_id"));
String strQue_Type = cur.getString(cur.getColumnIndex("question_type"));
String strQue_Nomber = cur.getString(cur.getColumnIndex("question_no"));
System.out.println("qid in checkUpdateTable() = " + qid);
System.out.println("strQue_Type in checkUpdateTable() = " + strQue_Type);
System.out.println("strQue_Nomber in checkUpdateTable()= " + strQue_Nomber);
QueId = qid;
databaseHelper.updateAnswerRow(qid, str_AnswerOptions);
}
}
}
catch (SQLiteException se )
{
Log.e(getClass().getSimpleName(), "Could not create or Open the database");
}
finally
{ if (sqdb != null) { sqdb.close();} }
}
}
}
You need to set a constraint on the table to trigger a "conflict" which you then resolve by doing a replace:
CREATE TABLE data (id INTEGER PRIMARY KEY, question_id INTEGER, question_type TEXT, question_no TEXT);
CREATE UNIQUE INDEX data_idx ON data(question_id);
Then you can issue:
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 2, 2, 3);
INSERT OR REPLACE INTO data VALUES (NULL, 1, 2, 5);

Parameter index out of range (1 > number of parameters, which is 0).; nested exception is java.sql.SQLException: [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 9 years ago.
I'm getting this error:
java.sql.SQLException: Parameter index out of range (1 > number of parameters, which is 0).
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1078)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:989)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:975)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:920)
at com.mysql.jdbc.PreparedStatement.checkBounds(PreparedStatement.java:3813)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3795)
at com.mysql.jdbc.PreparedStatement.setInternal(PreparedStatement.java:3840)
at com.mysql.jdbc.PreparedStatement.setInt(PreparedStatement.java:3784)
at com.mysql.jdbc.PreparedStatement.setObject(PreparedStatement.java:4052)
at org.springframework.jdbc.core.StatementCreatorUtils.setValue(StatementCreatorUtils.java:351)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValueInternal(StatementCreatorUtils.java:216)
at org.springframework.jdbc.core.StatementCreatorUtils.setParameterValue(StatementCreatorUtils.java:144)
at org.springframework.jdbc.core.ArgPreparedStatementSetter.doSetValue(ArgPreparedStatementSetter.java:65)
at org.springframework.jdbc.core.ArgPreparedStatementSetter.setValues(ArgPreparedStatementSetter.java:46)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:816)
at org.springframework.jdbc.core.JdbcTemplate$2.doInPreparedStatement(JdbcTemplate.java:1)
at org.springframework.jdbc.core.JdbcTemplate.execute(JdbcTemplate.java:587)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:812)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:868)
at org.springframework.jdbc.core.JdbcTemplate.update(JdbcTemplate.java:876)
When i'm trying to execute this class:
public List<CandidateDO> getCandidateList(final JobDO currentJob) {
List<CandidateDO> appliedCandidateList = new ArrayList<CandidateDO>();
CandidateDO candidate = new CandidateDO();
String query = "SET #sql = NULL;";
jdbcTemplate.execute(query);
query = "SELECT\n"
+ " GROUP_CONCAT(DISTINCT\n"
+ " CONCAT(\n"
+ " 'MAX(IF(`skillId` = ', `skillId`, ',levelId,NULL)) AS `',\n"
+ " `skillId`, '`'\n"
+ " )\n"
+ " ) INTO #sql\n"
+ "FROM tblCandidateToSkill,candidateToJob,tblCandidate\n"
+ "where tblCandidateToSkill.candidateId = candidateToJob.candidateId and tblCandidate.id = candidateToJob.candidateId;";
jdbcTemplate.execute(query);
query = "SET #sql = CONCAT('SELECT tblCandidateToSkill.candidateId,name,email,dob,phoneNumber,alternateNumber,addressLine, ', #sql, ' \n"
+ " FROM tblCandidateToSkill,candidateToJob,tblCandidate\n"
+ " where tblCandidateToSkill.candidateId = candidateToJob.candidateId and tblCandidate.id = candidateToJob.candidateId\n"
+ " and candidateToJob.jobId= ? \n"
+ " GROUP BY candidateId');";
jdbcTemplate.update(query, new Object[]{currentJob.getId()});
query = "PREPARE stmt FROM #sql;";
jdbcTemplate.execute(query);
query = "EXECUTE stmt;";
appliedCandidateList = jdbcTemplate.query(query, new RowMapper<CandidateDO>() {
#Override
public CandidateDO mapRow(ResultSet rs, int i) throws SQLException {
CandidateDO candidate = new CandidateDO();
candidate.setId(rs.getInt(1));
candidate.setName(rs.getString("name"));
candidate.setDob(rs.getDate("dob"));
candidate.setPhoneNumber(rs.getString("phoneNumber"));
candidate.setAlternateNumber(rs.getString("alternateNumber"));
candidate.setAddressLine(rs.getString("addressLine"));
for (Iterator<SkillDO> it = currentJob.getSkills().iterator(); it.hasNext();) {
SkillDO skill = it.next();
public List<CandidateDO> getCandidateList(final JobDO currentJob) {
List<CandidateDO> appliedCandidateList = new ArrayList<CandidateDO>();
CandidateDO candidate = new CandidateDO();
String query = "SET #sql = NULL;";
jdbcTemplate.execute(query);
query = "SELECT\n"
+ " GROUP_CONCAT(DISTINCT\n"
+ " CONCAT(\n"
+ " 'MAX(IF(`skillId` = ', `skillId`, ',levelId,NULL)) AS `',\n"
+ " `skillId`, '`'\n"
+ " )\n"
+ " ) INTO #sql\n"
+ "FROM tblCandidateToSkill,candidateToJob,tblCandidate\n"
+ "where tblCandidateToSkill.candidateId = candidateToJob.candidateId and tblCandidate.id = candidateToJob.candidateId;";
jdbcTemplate.execute(query);
query = "SET #sql = CONCAT('SELECT tblCandidateToSkill.candidateId,name,email,dob,phoneNumber,alternateNumber,addressLine, ', #sql, ' \n"
+ " FROM tblCandidateToSkill,candidateToJob,tblCandidate\n"
+ " where tblCandidateToSkill.candidateId = candidateToJob.candidateId and tblCandidate.id = candidateToJob.candidateId\n"
+ " and candidateToJob.jobId= ? \n"
+ " GROUP BY candidateId');";
jdbcTemplate.update(query, new Object[]{currentJob.getId()});
query = "PREPARE stmt FROM #sql;";
jdbcTemplate.execute(query);
query = "EXECUTE stmt;";
appliedCandidateList = jdbcTemplate.query(query, new RowMapper<CandidateDO>() {
#Override
public CandidateDO mapRow(ResultSet rs, int i) throws SQLException {
CandidateDO candidate = new CandidateDO();
candidate.setId(rs.getInt(1));
candidate.setName(rs.getString("name"));
candidate.setDob(rs.getDate("dob"));
candidate.setPhoneNumber(rs.getString("phoneNumber"));
candidate.setAlternateNumber(rs.getString("alternateNumber"));
candidate.setAddressLine(rs.getString("addressLine"));
for (Iterator<SkillDO> it = currentJob.getSkills().iterator(); it.hasNext();) {
SkillDO skill = it.next();
SkillLevelDO CandidateSkillLevel = new SkillLevelDO();
CandidateSkillLevel.setId(rs.getInt(String.valueOf(skill.getId())));
candidate.getSkillLevel().add(CandidateSkillLevel);
candidate.getSkills().add(skill);
}
return candidate;
}
});
query = "DEALLOCATE PREPARE stmt;";
jdbcTemplate.execute(query);
return appliedCandidateList;
} SkillLevelDO CandidateSkillLevel = new SkillLevelDO();
CandidateSkillLevel.setId(rs.getInt(String.valueOf(skill.getId())));
candidate.getSkillLevel().add(CandidateSkillLevel);
candidate.getSkills().add(skill);
}
return candidate;
}
});
query = "DEALLOCATE PREPARE stmt;";
jdbcTemplate.execute(query);
return appliedCandidateList;
}
Check out the reason for the error here.
Looks like the following query is having an issue.
query = "SET #sql = CONCAT('SELECT tblCandidateToSkill.candidateId,name,email,dob,phoneNumber,alternateNumber,addressLine, ', #sql, ' \n"
+ " FROM tblCandidateToSkill,candidateToJob,tblCandidate\n"
+ " where tblCandidateToSkill.candidateId = candidateToJob.candidateId and tblCandidate.id = candidateToJob.candidateId\n"
+ " and candidateToJob.jobId= ? \n"
+ " GROUP BY candidateId');";
Your single quotes (') is suspicious. The (?) PLACEHOLDER inside the query is within the Single quotes which is just considered as STRING rather than a (?) PLACEHOLDER.

Categories

Resources