Java-Output all the columns and rows of a ResultSet - java

ta.setText is a TextArea where I want to show all my data from the database, after a button click. But with rs.get("name") I just output one value and it is always the last. How can I print out the whole table from the database, so all the information which are stored there?
try { String newquery = "SELECT * FROM kunden";
java.sql.PreparedStatement ps = con.prepareStatement(newquery);
rs = ps.executeQuery(newquery);
while (rs.next()){
ta.setText(rs.getString("name"));
ta.setText(rs.getString("nachname"));
}
}// try
catch(Exception e1) {
JOptionPane.showMessageDialog(null, "fail");
}
}//actionperformed

Either you build a string an then set that string using setText()
StringBuilder builder = new StringBuilder();
while (rs.next()) {
builder.append(rs.getString(“name”));
builder.append(“ “);
builder.append(rs.getString(“nachname”));
builder.append(“\n“);
}
ta.setText(builder.toString());
Or you use the append method that exists for TextArea
while (rs.next()) {
ta.append(rs.getString(“name”));
ta.append(“ “);
ta.append(rs.getString(“nachname”));
ta.append(“\n“);
}

Related

Problem with diacritic, getting data from database java

I have MySQL database, where I have saved data and some words have diacritics.
This is my function how to get data from database.
public List<RowType> getData(String query){
List<RowType> list = new ArrayList<>();
try{
connect();
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query);
while(resultSet.next()){
StringBuilder str = new StringBuilder();
for(int i = 1; i <= getCountColumns(resultSet); i++){
if(i==1) str.append(resultSet.getString(i));
else str.append("," + resultSet.getString(i));
}
list.add(new RowType(str.toString()));
}
}
catch(Exception e){
System.out.println("Chyba při získavání údajů z databáze.");
System.out.println(e);
Console.print("Chyba při získavání údajů z databáze.");
Console.print(e.toString());
}
finally{
disconnect();
}
return list;
}
As parameter i send this query.
List<RowType> list = connection.getData("Select id from countries where name = 'Česko'");
But it doesn´t find anything, because i have diacritic in the query ("Česko"). I try it without diacritic and it works. So don´t you know how to fix it to work with accents too?
Can you try to add a few more queries before executing your main query?
so it will look something like:
connect();
Statement statement = connection.createStatement();
String query2 = "SET NAMES 'utf8'";
statement.execute(query2);
query2 = "SET CHARACTER SET 'utf8'";
statement.execute(query2);
ResultSet resultSet = statement.executeQuery(query);
if the above does not work for you, then maybe there is an issue with your database settings; if that's the case, you can refer to the answer here

How check whether a particular data exits in column

I am working on java swing project with database. There is a search by option (dropdown) to select by which attribute the user want to search and very next to dropdown their is a textfield where user can enter value and then click search. now i want to search for that particular value in that particular column(which is selected by user through the dropdowm) if it is exits i want to print them "found" if not then i want to display not found message.. Please find the attached images & code below.
For example: from dropdown if user select 'customer id' which is a column name and they enter id in the textfiled as '123456' then if it is exits in the column then i need to print found message else i need to print not found.
String column = jcombo2.getSelectedItem().toString();
String value = key.getText();
DefaultTableModel model = (DefaultTableModel) customerinfo.getModel();
DefaultTableModel model2 = (DefaultTableModel) customerinfo.getModel();
try {
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/customerinfo", "root", "");
Statement st = con.createStatement();
ResultSet rs;
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs =st.executeQuery(mysqlQuery);
while(rs.next()) {
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
}catch(Exception e) {
System.out.println(e.getMessage());
}
Try this:
String mysqlQuery = "SELECT COUNT(*) FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
if (rs.next() && (rs.getInt(1) != 0))
printFoundIt(); // or whatever you want to do
else
printDidntFindIt(); // or whatever you want to do
st.close();
Or in case you want to fill the table with found items contemporarily:
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
boolean found_it = false;
while (rs.next())
{
found_it = true;
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
st.close();
if (found_it)
printFoundIt(); // or whatever you want to do
else
printDidntFindIt(); // or whatever you want to do
Same as before but printing the 'found it' directly after having found the first element:
String mysqlQuery = "SELECT * FROM `cust_info` WHERE `"+column+"` ='"+value+"'";
rs = st.executeQuery(mysqlQuery);
boolean found_it = false;
while (rs.next())
{
if (!found_it)
{
printFoundIt(); // or whatever you want to do
found_it = true;
}
String ci = rs.getString("customer id");
model.addRow(new Object[] {ci});
}
st.close();
if (!found_it)
printDidntFindIt(); // or whatever you want to do

Update one column from table and insert new rows. sqlite, java

I have some problems to modify data from a table.
I need to update an entire column from a specific table and if there's no sufficient rows I need to insert more.
More exactly, the user will be able to modify data from interface, in a text area that contains current data from db.
I put all the text in a list, each line representing an element of the list.
In a certain column, I must go through each row and modify it with a list item. If there are more lines in the text area than number of rows in that table, I need to insert new ones, which will contain the remaining items from the list.
I would be grateful if someone could give me some help.
Thanks!
#FXML
public void modify() throws SQLException {
String col= selectNorme.getValue().toString();
String text=texta.getText();
List<String> l1notes= new ArrayList<>( Arrays.asList( text.split("\r\n|\r|\n") ));
Statement stmt=null;
String client = this.clientCombobox.getValue().toString();
String tab1Client= client+ "_" +this.selectLang1.getValue().toString();
String query="SELECT * FROM "+tab1Client+" WHERE ["+ selectNorme.getValue().toString()+ "]= "+col+"";
String sqlUpdate1= "UPDATE ["+tab1Client+"] SET ["+ this.selectNorme.getValue().toString() +"] = ?";
try {
Connection conn = dbConnection.getConnection();
PreparedStatement modif=conn.prepareStatement(sqlUpdate1);
int i=0;
if (rss.next()) {
stmt = conn.createStatement();
rss = stmt.executeQuery(query);
stmt.executeUpdate(sqlUpdate1);
modif.setString(1, l1notes.get(i));
i++;
modif.execute();
}
else {
PreparedStatement pstmt = conn.prepareStatement("INSERT INTO ["+this.clientCombobox.getValue().toString()+"_"+this.selectLang1.getValue().toString()+"] (["+ this.selectNorme.getValue().toString() +"]) values (?)" );
for (int row=i; row< l1notes.size(); row++)
{
pstmt.setString(1, l1notes.get(row));
pstmt.executeUpdate();
}
}
}
finally {
try {
if (conn !=null)
conn.close();
}
catch (SQLException se){
se.printStackTrace();
}
}
}

Java sql text from database

i have a label and i want to upload with text from database, i wrote a method but its show just the first item from database, i want to see all item in column
try {
String sql="SELECT * FROM Arlista";
PreparedStatement pst=conn.prepareStatement(sql);
ResultSet rs=pst.executeQuery();
while(rs.next()) {
arlab1.setText(rs.getString("nev"));
}
}catch(Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
while(rs.next()) {
arlab1.setText(rs.getString("nev"));
}
...overwrites the content of arlab each iteration. What you probably want to do is some kind of append to the result for each row;
String result = "";
while(rs.next()) {
if(result.isEmpty()) result = rs.getString("nev");
else result = result + "/" + rs.getString("nev");
}
arlab1.setText(result);

compare integer text field value with mysql data in java

I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}

Categories