Adding database column to JComboBox - java

I've searched around for the answer to this, but to no avail. When I compile this, it just returns the last row of my table in the database and not a list of the entire column as I expect. I believe the problem is from here.. If only I can make it list everything in that column, I'd be grateful for your help.
String query = "SELECT contact_id, first_name, last_name FROM my_contacts";
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
String name = rs.getString(2) + " " + rs.getString(3);
names = new JComboBox();
names.addItem(rs.getString("first_name"));
}//end while

When I compile this, it just returns the last row of my table in the
database and not a list of the entire column as I expect. I believe
the problem is from here..
while (rs.next())
{
System.out.println(rs.getInt(1) + " " + rs.getString(2) + " " + rs.getString(3));
String name = rs.getString(2) + " " + rs.getString(3);
names = new JComboBox();
names.addItem(rs.getString("first_name"));
}
your code created a new instance of JComboBox, in each of loop inside while (rs.next()){
create JComboBox as local variable, then just to add Items in while-loop to instance that already exist and is intialized
best of ways is by using DeafultComboBoxModel for add / remove / modify an Items for JComboBox

Got everything up and running with this code.
try {
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/recall", "username", "password");
Statement statement = connection.createStatement();
String query = "SELECT * FROM names";
ResultSet rs = statement.executeQuery(query);
while (rs.next())
{
String name = rs.getString("name");
names.addItem(rs.getString("name"));
}//end while
connection.close();
} catch (Exception e) {
e.printStackTrace();
}

Related

Searching the Mysql database with Autocomplete on JTable using textfield

Could you please tell me what to add on my code so that when i type a letter in the textfield, before i finish typing the search result already start showing on jtable without waiting for me to type the whole word?
Below please find my code for key released event on the textbox. Thank you for your help.
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try{
String selected=(String)jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"
+ "employee_certificate","root","");
String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n" +
"certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+ "WHERE "+selected+" =? ORDER BY stuff.Emp_Name\n" ;
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1, jTextFieldSearch.getText());
ResultSet rs=pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
//con.close();
}
catch(Exception ex){ex.printStackTrace();}
}
After a two day struggle finally i got an answer...i just needed to use LIKE '%' as shown.No one should suffer as i did
private void jTextFieldSearchKeyReleased(java.awt.event.KeyEvent evt) {
try{
String selected=(String)jComboBoxSelected.getSelectedItem();
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"+ "employee_certificate","root","");
String sql="SELECT stuff.Emp_Id,stuff.Emp_Name, stuff.Department, "
+ "certificate.Cert_Code, certificate.Cert_Name,\n" +
"certificate.Cert, certificate.Vendor, certificate.Date_Taken, "
+ "certificate.Expiry_Date FROM stuff LEFT JOIN certificate"
+ " ON stuff.Emp_Id=certificate.Emp_Id "
+"WHERE "+selected+" LIKE ? ORDER BY stuff.Emp_Name\n" ;
PreparedStatement pstmt=con.prepareStatement(sql);
pstmt.setString(1,jTextFieldSearch.getText() + "%");
ResultSet rs=pstmt.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
pstmt.close();
con.close();
}
catch(Exception ex){ex.printStackTrace();}
}

Populating jTable from postgresql

I am doing java project in NetBeans 8 using databases and GUI.The problem is appearing when I search through the database and add the found values to JTable: all values are being added only to first column of JTable while I need them added separately to corresponding columns. I tried getColumnCount() and it also gave me 1 meaning that I have only one column. How to add database values to JTable's corresponding columns?
I've tried all the populating functions adviced here
My code:
jTable1 = new javax.swing.JTable();
String sql = "SELECT (flight_id, plane_name, dep_city, arival_city, date_month, date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats) FROM flight "
+ "WHERE (dep_city = '" + SearchFlight.getFromCity() + "' AND "
+ "arival_city = '" + SearchFlight.getToCity() + "' AND "
+ "date_month = '" + SearchFlight.getMonth() + "');";
PreparedStatement stat = conn.prepareStatement(sql);
ResultSet rs = stat.executeQuery();
jTable1.setModel(DbUtils.resultSetToTableModel(rs)
);
jScrollPane1.setViewportView(jTable1);
SearchFlight is a GUI class, and its methods return strings obtained in GUI.
DbUtils.resultSetToTableModel(rs)is a method in net.proteanit.sql.DbUtils;
So, it is expected that the data will be filled into 9 columns, hoewever it fills all the data into one column.
SELECT ( ... )
must be
SELECT ....
And better use the PreparedStatement as intended. Otherwise SQL injection still is possible. And try-with-resources closes the things under all circumstances.
String sql = "SELECT flight_id, plane_name, dep_city, arival_city, date_month, "
+ "date_day, eclassnumberofseats, bclassnumberofseats, fclassnumberofseats "
+ "FROM flight "
+ "WHERE dep_city = ? AND "
+ "arival_city = ? AND "
+ "date_month = ?";
try (PreparedStatement stat = conn.prepareStatement(sql)) {
stat.setString(1, SearchFlight.getFromCity());
stat.setString(2, SearchFlight.getToCity());
stat.setString(3, SearchFlight.getMonth());
try (ResultSet rs = stat.executeQuery()) {
jTable1.setModel(DbUtils.resultSetToTableModel(rs));
}
}

Ambiguous column using JDBC but query works fine in database

I am connecting to a SQLite database through java using JDBC.
Schema:
WorkInfo(id, job, salary)
Person(id, name)
This query below runs fine in my database, but when I try it with JDBC:
ResultSet rs = statement.executeQuery("select * from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("Person.id")); //column does not exist
System.out.println("name: " + rs.getString("name")); //works fine
Output:
If using person.id: no such column: 'person.id'
Without specifying: ambiguous column name 'id'
I've tried using both WorkInfo and Person and using aliases but it keeps throwing the same ambigious column name (if left as id) or column does not exist.
It's always a good practice to explicitly retrieve the columns you want. I would change the query to be:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id, person.name from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt(4));
System.out.println("name: " + rs.getString(5));
In this case, you can use the column index instead of the label.
Or using the AS clause:
ResultSet rs = statement.executeQuery("select info.id, info.job, info.salary, "
+ "person.id as personId, person.name as personName "
+ "from Person person join workInfo info "
+ "on person.id=info.id");
while(rs.next()){
System.out.println("id: " + rs.getInt("personId"));
System.out.println("name: " + rs.getString("personName"));
After a day of working on this, I achieved it by using resultSet.getMetaData().
private int getIndexFromMeta(String column) {
try {
ResultSetMetaData meta = resultSet.getMetaData();
String[] subs = column.split("\\.", -1);
String tableName = subs[0];
String columnName = subs[1];
for (int i = 1; i <= meta.getColumnCount(); i++) {
if (meta.getTableName(i).equals(tableName) && meta.getColumnName(i).equals(columnName)) {
return i;
}
}
} catch (SQLException e) {
Log.trace(e);
}
return 0;
}
It seems like the ResultSet you're getting back holds the following columns:
id
name
id
job
salary
You have two columns named "id" (none named "Person.id"), so when you try to get its' value you either
Ask for "id" which is ambiguous (which id?)
Ask for "Person.id" which does not exist
Simply try specifying in your query the columns you want and giving them unique aliases. For example:
ResultSet rs = statement.executeQuery("select Person.id AS 'personid', name from Person join workInfo on (Person.id=WorkInfo.id)");
while(rs.next()){
System.out.println("id: " + rs.getInt("personid"));
System.out.println("name: " + rs.getString("name"));

Java SQL (JDBC) : how to move to the next column?

I'm trying to check if the "Username" and "Email" arguments in my constructor are existed in the SQL Table.
this is my code:
public DB(String usr, String eml, String pwd) {
this.usr = usr;
this.eml = eml;
this.pwd = pwd;
String jdbcUrl = "jdbc:mysql://localhost:3306/registered";
String jdbcUser = "....";
String jdbcPassword = "....";
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcUrl, jdbcUser,
jdbcPassword);
statement = connection.createStatement();
now , if i use SELECT with two columns, like this:
String command = "SELECT UserName,Email FROM users WHERE UserName LIKE '" + this.usr.toString() + "';";
resultSet = statement.executeQuery(command);
and then do my loop for resultSet... like this:
while (resultSet.next()) {
if (usr.equalsIgnoreCase(resultSet.getString("UserName"))) {
System.out.println("UserName : " + this.usr + " is taken!");
}
else if (eml.equalsIgnoreCase(resultSet.getString("Email"))) {
System.out.println("Email : " + this.eml + " is taken!");
}
else {
System.out.println("Email : " + this.eml + " and UserName : " + this.usr + " are AVAILABLE!");
command = "INSERT users SET UserName = '" + this.usr.toString() + "',Email = '" + this.eml.toString() + "',Password = '" + this.pwd.toString() + "',Status = '0' ,Connected = '1';";
statement.executeUpdate(command);
}
}
} catch (SQLException e) {
System.out.println("SQLException: " + e.getMessage());
System.out.println("Vendor error: " + e.getErrorCode());
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
the
resultSet.next()
only runs over the "FIRST" column which means
if the "usr" exists in the table it works,
but if the "usr" does not exist in the table, the other two if statements does-not work ..
,... i want to check both first column and second,.. and maybe third or more soon.. , any help?
Your WHERE clause only tests for the UserName, so if the UserName doesn't match this.usr.toString(), the resultSet will be empty, so the while loop won't be entered.
You should change the query to match all the fields you care about - something like - "SELECT UserName,Email FROM users WHERE UserName = ... OR Email = ..."
If the resultSet is empty, you'll know that you can insert the new record. Otherwise, you can check which of the fields (UserName, Email) is already taken.
One more thing you should be aware of - executing a SQL statement without PreparedStatement makes your code vulnerable to SQL injection attacks.
You should change your code to something like this :
PreparedStatement pstmt = con.prepareStatement("SELECT UserName,Email FROM users WHERE UserName = ? OR Email = ?");
pstmt.setString(1, this.usr);
pstmt.setString(2, this.eml);
resultSet = pstmt.executeQuery();
You should change your INSERT statement similarly to use PreparedStatement.

JDBC's rs.getString() won't return the value of the query result

I have some problems with JDBC's rs.getString("column_name") basically it would not assign the value recieved from the query result, I have a String ris which is supposed to get the row name from rs.getString, for semplicity of the question I'm using ris and my query returns only one row. This is the code:
//It returns null, or any other values I use to initialize the variable
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
if (!rs.last()) {
ris = "no";
}
else {
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();
} catch (Exception e) {
ris = e.toString();
}
return ris;
I semplified the code, so it would be easy to focus on where the problem is.
Thanks in advance!
if (rs.last())
while (rs.next())
That won't work, because after you have called last , you are at the last row and next will always return false (it would return true and take you to the next row if there was one left).
And please use a prepared statement with bind variables!
And finally close ResultSet and Connection (or use Jakarta Commons DbUtils).
try this, just remove the rs.last() call in the if condition.. also i agree with #Thilo about using prepared statements.
String ris=null;
q = "SELECT DISTINCT nome FROM malattia WHERE eta='" + age + "' AND sesso='" + sexstr + "' AND etnia='" + etniastr + "' AND sintomi IN(" + tes + ")";
ResultSet rs = st.executeQuery(q);
rs.first(); // go to first record.
//This is the place where I'm having problems
while(rs.next()){
//ris is supposed to get the name of the query result having column "nome"
ris=rs.getString("nome");
}
}
conn.close();

Categories

Resources