How check whether a particular data exits in column - java

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

Related

Java-Output all the columns and rows of a ResultSet

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“);
}

Parameter index out of range

I tried to create a login form and it is showing Column index is out of range. I have created two columns and I have used two columns but it is showing error.
String url = "jdbc:mysql://localhost:3306/login_form?useSSL=false";
String name = "Vzlys";
String Pass = "Vzlys#1995";
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url,name,Pass);
st = con.prepareStatement("select * from login where username = ? and password = ?");//here login is my table name
st.setString(1,txtusername.getText());
st.setString(2,txtpassword.getText());//error occurs here
rs = st.executeQuery();
JOptionPane.showMessageDialog(null,"Welcome");
ferrysql f = new ferrysql();
f.setVisible(true);
con.close();
st.close();
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
In your code:
st = con.prepareStatement("query");
Means your query is : query
But if you use ;
String query= "select * from table A where column1 = ?";
st = con.prepareStatement(query);
Note: in this staement query is not within inverted commas.
Hope this will help.
st = con.prepareStatement("query");
Above line shows that your query is "query" not the variable, which you might have been used in your program
It may be due to your txtpassword.getText() is null at line
st.setString(2,txtpassword.getText());
print both txtusername and txtpassword to check both filed contains data or not before using at preparedStatement
If you are checking user name and password then you have to use following query
PreparedStatement st = con.prepareStatement("select * from user where
(userName = ? and password = ?");
st.setString(1,txtusername.getText());
st.setString(2,txtpassword.getText());
This should work

Java: SQL Query: rs.next() is false after updating a column

I have a strange problem. I have a database and I want to change the values of a column. The values are safed in an Arraylist (timelist).
In order to write the values in the right row, I have a second Arrylist (namelist). So I want to read the first row in my Database, than I check the namelist and find the name. Than i take the matching value out of the timelist and write it into the database into the column "follows_date" in the row, matching to the name.
And than I read the next row of the Database, until there are no more entries.
So the strange thing is, if I change nothing in the database, the while(rs.next()) part works.
For example:
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //liest die namen
}
}
This would print me every name after name. But when I change the table, the while loop ends after that. (no error, the program just finishes)
ResultSet rs = statement.executeQuery("SELECT username FROM users");
while(rs.next()){
// read the result set
String name = rs.getString("username");
System.out.println("username = " + name); //writes the name
//look, if name is in Arraylist "namelist"). if yes, than write the matching date from "timelist" into the database.
if (namelist.contains(name)){
System.out.println("name found: "+ name);
int listIndizi = namelist.indexOf(name); //get index
Long indiziDatum = (long) timelist.get(listIndizi); //get date from same Index
System.out.println(indiziDatum); // print date so i can see it is correct (which it is)
statement.executeUpdate("UPDATE users SET follows_date ="+ indiziDatum +" WHERE username = '"+name+"'"); //updates the follows_date column
}
}
Everything works fine, except that now, the while loop doesn't continues after the first passage, but ends.
The resultSet of a statement is closed and will not return further results if you execute another statement. Create a new separate statement object for the update and everything should work as excepted.
Statement statement1 = connection.createStatement();
Statement statement2 = connection.createStatement();
ResultSet resultSet1 = statement1.executeQuery("SELECT username FROM users");
while(resultSet1.next()){
...
statement2.executeUpdate("UPDATE users ..."));
}
As to Why it happens:
Here is the explanation from the official documentation:
A ResultSet object is automatically closed when the Statement object that generated it is closed, re-executed, or used to retrieve the next result from a sequence of multiple results.
Alternative Approach:
From your sample, it seems you are trying to update the "same" row in your resultSet, you should consider using an Updatable ResultSet.
Sample code from the official documentation:
public void modifyPrices(float percentage) throws SQLException {
Statement stmt = null;
try {
stmt = con.createStatement();
stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet uprs = stmt.executeQuery(
"SELECT * FROM " + dbName + ".COFFEES");
while (uprs.next()) {
float f = uprs.getFloat("PRICE");
uprs.updateFloat( "PRICE", f * percentage);
uprs.updateRow();
}
} catch (SQLException e ) {
JDBCTutorialUtilities.printSQLException(e);
} finally {
if (stmt != null) { stmt.close(); }
}
}

Deleting selected row in MySQL database through JTable

tb_records = jtable name
records = table name inside my database
Date = my first column
hey = substitute for my real password
mydatabase = name of my database
My problem is that, when I highlight a row in my JTable and delete it, it deletes all the rows. I want to delete the selected row only. Here's my code:
int row = tb_records.getSelectedRow();
DefaultTableModel model= (DefaultTableModel)tb_records.getModel();
String selected = model.getValueAt(row, 0).toString();
if (row >= 0) {
model.removeRow(row);
try {
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase", "root", "hey");
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
ps.executeUpdate();
}
catch (Exception w) {
JOptionPane.showMessageDialog(this, "Connection Error!");
}
}
What could be the problem here? How can I delete a selected row in my database and not all the rows?
DefaultTableModel model = (DefaultTableModel) jTable.getModel();
int row = jTable.getSelectedRow();
String eve = jTable.getModel().getValueAt(row, 0).
String delRow = "delete from user where id="+eve;
try {
ps = myCon.getConnection().prepareStatement(delRow);
ps.execute();
JOptionPane.showMessageDialog(null, "Congratulation !!");
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e.getMessage());
}
1) Don't display your own message. Display the error message from the Exception as it will give a better explanation what the problem is.
2) Use a proper PreparedStatement for the SQL. You are less likely to make syntax errors. Something like:
String sql = "delete from records where Date= ?";
PreparedStatement stmt = connection.prepareStatement(sql);
stmt.setString( 1, selected );
stmt.executeUpdate();
I don't know much about SQL but maybe you need to pass a Date object not a String object since your where clause is using a Date?
The OP wrote:
SOLUTION: Pick a column with unique values. My Date column has the same values that's why it's deleting all my rows even though I set my row as getSelectedRow. Time_in = my 4th column with unique values.
change
String selected = model.getValueAt(row, 0).toString();
to
String selected = model.getValueAt(row, 3).toString();
and
PreparedStatement ps = conn.prepareStatement("delete from records where Date='"+selected+"' ");
to
PreparedStatement ps = conn.prepareStatement("delete from records where Time_in='"+selected+"' ");

Retrieving data based on the ID java

i wanted to retrieve the data from the database with ID.. So, i wanted to do like this: i have number on my combobox 1 to 4. Whenever i select 1 in combobox, the textbox firstname and lastname text will be change based on the selected id. How do i do that?
I already tried like this, but it won't work:
private void Edit(Connection conn, Statement state, ResultSet result)
{
try
{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String url = "jdbc:odbc:Database";
conn = DriverManager.getConnection(url);
String query = "select FirstName, LastName, Status, JoinedDate from Customer where ID = ?";
PreparedStatement statement = conn.prepareStatement(query);
statement.setInt(1, jComboBox1.getSelectedIndex());
result = statement.executeQuery();
while(result.next())
{
jTextField3.setText("FirstName");
jTextField2.setText("LastName");
jTextField3.setText("Status");
JoinedDateLabel.setText("JoinedDate");
}
}
catch (Exception e)
{
System.err.println(e.getMessage());
_sound.PlaySound(2);
_infoBox.ShowMessageBox(e.getMessage(), "Error", 2);
_reminder = new Reminder(1);
JOptionPane.showOptionDialog(null, "Program will be closed due to error!", "Error", JOptionPane.DEFAULT_OPTION, JOptionPane.INFORMATION_MESSAGE, null, new Object[]{}, null);
System.exit(0);
}
Thank you
Try this
while(result.next())
{
jTextField1.setText(result.getString("FirstName"));
jTextField2.setText(result.getString("LastName"));
jTextField3.setText(result.getString("Status"));
JoinedDateLabel.setText(result.getString("JoinedDate"));
}
All you're doing with your current code is setting the text to the strng literal "FirstName". You need to actually retrieve the data from the ResultSet and set the text as that data.
Also, note JComboBox indices are 0 based. So if you are selecting the first index, it would return 0. You should make sure (in your case) that the db has Id's of 0,1,2,3

Categories