How can I pass string to a JOptionPane? - java

I have tried to write a code that searches a database of students and shows the searched result on a option pane. And I ended up writing the following. The expected result is:
Name: "something"
Roll: "something"
Registration: "Something"
But actually the output is something like this:
Name: null
Roll: null
Registration: null
public class Search
{
JFrame sw = new JFrame("Search Students' Info"); //search window
JTable stable;
JLabel stfl = new JLabel("Roll"); //search text field label
JTextField stf = new JTextField(8); //search text field
JButton sb = new JButton("Search"); //search button
public void exsearch() //Execute Search
{
sw.setLayout(new GridLayout(2,2));
sw.add(stfl);
sw.add(stf);
sw.add(sb);
sw.setSize(200, 100);
sw.setLocation(100, 100);
sw.setVisible(true);
sb.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/srsdb";
try
{
Class.forName(driver).newInstance();
java.sql.Connection con = DriverManager.getConnection(url, "root", "");
JOptionPane.showMessageDialog(null, "Connected", "Connection Confirmation", JOptionPane.PLAIN_MESSAGE);
String str ="SELECT* FROM students WHERE Roll="+stf.getText();
java.sql.Statement st = con.createStatement();
java.sql.ResultSet rs = st.executeQuery(str);
rs.first();
int n = rs.getMetaData().getColumnCount();
// String[] columnnNames;
String[] attributes= new String[10];
int j;
while(rs.next())
{
for(j=0; j<3; j++)
{
attributes[j] = rs.getString(j);
}
}
JOptionPane.showMessageDialog(null, "Name :"+attributes[0]+"\nRoll :"+attributes[1]+"\nRegistration :"+attributes[2], "Search Result", JOptionPane.PLAIN_MESSAGE);
}
catch(Exception f)
{
f.printStackTrace();
JOptionPane.showMessageDialog(null, "Not Found", "Search Result", JOptionPane.PLAIN_MESSAGE);
}
}});
}
public static void main (String[] args)
{
new Search();
}
}

I would use a debugger to check which part of your code is omitted.
One wierd thing I see is, that you jump to the first record in your result set:
rs.first();
And then you read the data from all subsequent records in a while loop
while(rs.next())
{
for(j=0; j<3; j++)
{
attributes[j] = rs.getString(j);
}
}
This ensures, that you get the data from the last matching record if there is more than one.
Better would be to check if there is zero or more than one record. If that is the case, issue a warning because probably there is something wrong with your code (use a debugger to find out what).
If there is only one record, read the data from that record and print it (more or less like you try with rs.getString())

Class.forName ensures that the driver class is on the class path, without needing to compile against the class. It loads the class. No instantiation needed.
A PreparedStatement is better against SQL injection.
Column numbers in the SQL API are 1-based: 1, 2, 3, ... A bit of an exception.
When using first the query loop is as follows. You skipped the first row I think.
Do not forget the miscellaneous close().
Better style to list the columns instead of `*'.
Hence:
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/srsdb";
try
{
Class.forName(driver);
Connection con = DriverManager.getConnection(url, "root", "");
JOptionPane.showMessageDialog(null, "Connected",
"Connection Confirmation", JOptionPane.PLAIN_MESSAGE);
String str ="SELECT Name, Registration FROM students WHERE Roll=?";
PreparedStatement st = con.createPreparedStatement(str);
String roll = stf.getText();
st.setString(1, roll);
String message = "";
java.sql.ResultSet rs = st.executeQuery();
int recno = 0;
if (rs.first()) {
do {
String name = rs.getString(1);
String registration = rs.getString(2);
++recno;
message += "- " + recno + " -\nName: " + name
+ "\nRoll: " + roll
+ "\nRegistration: " + registration + "\n";
} while (rs.next());
}
rs.close();
JOptionPane.showMessageDialog(null, message, "Search Result",
JOptionPane.PLAIN_MESSAGE);

Related

Problem in extracting the result of a query

I just want to get two columns text and aid based on a condition and put the result in two arrays one for each column but only one column I'm able to extract as when I try to get the other as in the code below it gave me white page! When I remove one and leave the other it works whatever which column it only works in one only so what is the problem?
<%
String url = "jdbc:mysql://localhost:3306/fci";
String user = "root";
String password = "root";
Statement Stmt = null;
ResultSet RS = null;
Connection Con = null;
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
Con = DriverManager.getConnection(url, user, password);
Stmt = Con.createStatement();
String queryString2 = " select aid,text from ans where qid=1" ;
RS = Stmt.executeQuery(queryString2);
String[] answers = {"0","0","0"};
String[] answers_id = {"0","0","0"};
int count=0;
while(RS.next())
{
answers[count++] = RS.getString("text");
answers_id[count++]=RS.getString("aid");
for(int i =0; i< 3 ; i++)
{
out.println(answers[i] );
out.println(answers_id[i]);
}
Con.close();
RS.close();
} catch (Exception cnfe) {
System.err.println("Exception: " + cnfe);
Your problem is that you are double-incrementing count in your loop, resulting in an array index that is out of bounds. Change
answers[count++] = RS.getString("text");
answers_id[count++]=RS.getString("aid");
To
answers[count] = RS.getString("text");
answers_id[count++]=RS.getString("aid");
and that should solve your problem.

checking duplicate for more than two values, if no such duplicate then insert query

Note:
I have two columns (Name(primary key), Email(primary key))
I have inserted two rows.
The 1st row, where name=ema email=ema#gmail.com, and my 2nd row where name=ena email=fe.
Now, when I want to insert a new record it only checks with the 1st row and the checking works, but if I want to insert name=ena and email=something it does not check for the second row. Can someone please suggest to me how do I overcome this?
try
{
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
//block of code to check user exists or not.
//Statement statement = connection.createStatement();
PreparedStatement Pstatement;
String query = "select Name,Email from detail";
PreparedStatement ps = connection.prepareStatement(query);
ResultSet rs = ps.executeQuery() ;
if(rs.next())
{
//from database
String name_db1 = rs.getString("Name").trim(); //using trim removes all white spaces
String email_db2 = rs.getString("Email").trim();
//from user GUI
String entered_name = name.getText().trim(); //using trim removes all white spaces
String entered_email = email.getText().trim();
boolean valid = true;
if(entered_name.equals(""))
{
JOptionPane.showMessageDialog(null,"Enter name");
valid = false;
}
else if(name_db1.equals(entered_name))
{
JOptionPane.showMessageDialog(null,"Enter name taken");
name.setText(null);
valid = false;
}
else if(entered_email.equals(""))
{
JOptionPane.showMessageDialog(null,"Enter email");
valid = false;
}
else if(email_db2.equals(entered_email))
{
JOptionPane.showMessageDialog(null,"email taken");
email.setText(null);
valid = false;
}
else if(valid == true)
{
Pstatement=connection.prepareStatement("insert into detail values(?,?)");
//Specifying the values of preparestatement parameter
Pstatement.setString(1,name.getText());
Pstatement.setString(2,email.getText());
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null,"registration successful");
//x++;
}
}
else
{
//incase if the user click without filling up the fields
JOptionPane.showMessageDialog(null,"not yet registered");
}
}
catch(SQLException e)
{
e.printStackTrace();
}
Finally, I have figured out the logic, I just need to create a separate query for both Name and Email. This way I can search more than two values :D. If there is any mistake please let me know.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/testing","root","");
//creating a query for Name
String query1 = "select Name, Email from detail where Name like '"+name.getText()+"'";
PreparedStatement statement1 = con.prepareStatement(query1);
//creating a query for Email
String query2 = "select Name, Email from detail where Email like '"+email.getText()+"'";
PreparedStatement statement2 = con.prepareStatement(query2);
ResultSet result1 = statement1.executeQuery(); //resultset for name
ResultSet result2 = statement2.executeQuery(); //resultset for email
//checking name exception
if (result1.next())
{
String dbasename=result1.getString("Name").toString().trim();
String enteredname=new String(name.getText().trim());
if(enteredname.equals(""))
{
JOptionPane.showMessageDialog(null, "enter name");//valid1 = false;
}
else if(dbasename.equals(enteredname))
{
JOptionPane.showMessageDialog(null, "name taken");//valid1 = false;
name.setText(null);
}
}
//checking email exception
else if(result2.next())
{
String dbaseemail=result2.getString("Email").toString().trim();
String enteredemail=new String(email.getText().trim());
if(enteredemail.equals(""))
{
JOptionPane.showMessageDialog(null, "enter email");//valid1 = false;
}
else if(dbaseemail.equals(enteredemail))
{
JOptionPane.showMessageDialog(null, "email taken");//valid1 = false;
email.setText(null);
}
}
//if no exception is detect exectute the below statement
else
{
PreparedStatement Pstatement=con.prepareStatement("insert into detail values(?,?)");
Pstatement.setString(1,name.getText());
Pstatement.setString(2,email.getText());
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null,"Registered Successfully");
}
statement1.close();
statement2.close();
con.close();
}
catch(SQLException se){
se.printStackTrace();
}
catch(Exception e)
{
e.printStackTrace();
JOptionPane.showMessageDialog(null, "error during searching");
}

remove last word continuously and check in database table java

i have a small translation program to develop. The user input a sentence and the sentence is then check in a table in my database. if the sentence to sentence match is found. it displays the result else it removes the last word of the sentence and rechecks until a match is found or until one word is left( to be developed) . i have a small implementation for the handling of sentence to sentence match but i am having a small problem with my loop. i cannot figure out out to make it work. I know the problem is the the else part of loop i cannot figure out how to do it. I am not sure if the compiler will even loop back for the truncated sentence.
String sentence = "i am a good boy";
for(int j=0;j<sentence.length();j++)
{
if(sentence.length()>1)
{
sentence = lookUpSentencePart(sentence);
rs2 = sentenceDBQuery(sentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
System.out.println("mon pass dan rs1 true");
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
else
{
sentence = lookUpSentencePart(sentence);
rs2 = sentenceDBQuery(sentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
}
}
}
public String lookUpSentencePart(String sentence)
{
sentence = sentence.substring(0, sentence.lastIndexOf(" "));
return sentence;
}
public ResultSet sentenceDBQuery(String sentence, String source, String target)
{
ResultSet rs = null;
Statement stmt;
myConnection db = new myConnection();
try
{
Connection myConn = db.theconnect();
stmt = myConn.createStatement();
rs = stmt.executeQuery("SELECT " + target + " from sentence WHERE " + source + " = '" + sentence+"'");
}
catch(SQLException e)
{
e.printStackTrace();
}
return rs;
}
Probably you need smth like that :) You still need to add some boundary checks
String[] sentence = "i am a good boy".split(" ");
for(int j=0;j<sentence.length;j++)
{
String realSentence = buildSentence(sentence, j);
rs2 = sentenceDBQuery(realSentence,srcLanguage,targLanguage);
if(rs2.first()==true)
{
System.out.println("mon pass dan rs1 true");
sb1.append(rs1.getString(targLanguage));
sentencePart = sb1.toString();
System.out.println(sentencePart);
}
}
public String buildSentence(String[] parts, int index) {
StringBuilder result = new StringBuilder();
for (int j = 0; j < (parts.length - index); j++) {
sb.append(parts[j]).append(" ");
}
sb.setLength(sb.length() - 1);
return result.toString();
}

Schema 'TEST' does not exist

I'm new to creating Java programs with a DB connection. I'm trying to get the program to create a table, read a table in so that I can then have queries run and show certain data. From what I can tell I have my program connecting to the DB successfully but I'm receiving the error:
Syntax error: Encountered ")" at line 8, column 1.
Schema 'TEST' does not exist
Schema 'TEST' does not exist
Schema 'TEST' does not exist
Schema 'TEST' does not exist
Other errors, I'm used to receiving the line # so that I at least know where to start looking. With a line and column #, I'm not sure and I have looked through other posts and tried to make the updates like making APP the default schema. A helpful push in the right direction as to where to start looking. Once I figure out how to get past this and have the query print, I know I'll be good to go. Thanks for any help offered.
import static java.lang.System.out;
import java.sql.*;
import java.sql.SQLException;
public class AnimalDB1 {
private static final String url = "jdbc:derby://localhost:1527/AnimalDB;create=true;user=test;password=test";
private static final String tableName = "Animal";
private static Connection conn = null;
private static int nextId = 1;
private boolean tablesCreated = false;
private static void createConnection(){
try{
System.out.println("Connecting to Database...");
conn = DriverManager.getConnection(url);
System.out.println("Database Connection Successful\n");
}
catch (SQLException e){}
}
// Increments the ID number for each animal
private void incId(){
AnimalDB1.nextId++;
}
private void animalTable() throws SQLException{
Statement statement = null;
try{
StringBuilder sb = new StringBuilder("");
sb.append("CREATE table Animal (\n");
sb.append("ID INTEGER NOT NULL,\n");
sb.append("AnimalName varchar(15),\n");
sb.append("Char1 varchar(15),\n");
sb.append("Char2 varchar(15),\n");
sb.append("Char3 varchar(15),\n");
sb.append("Char4 varchar(15),\n");
sb.append(")\n");
// Get a statement from the connection so we can execute the query.
statement = conn.createStatement();
statement.executeUpdate(sb.toString());
tablesCreated = true;
} catch (Exception e){
System.out.println(e.getMessage());
} finally {
if(statement != null){
try {
statement.close();
}
catch(Exception e){
System.err.println(e.getMessage());
System.exit(0); // Something is terribly wrong so just quit the program.
}
}
}
}
private void createAnimal (String animalName, String char1, String char2, String char3, String char4){
PreparedStatement pState = null;
try{
String sql = "Insert into Animal values (?,?,?,?,?,?)";
pState = conn.prepareStatement(sql);
pState.setInt(1, nextId);
pState.setString(2, animalName);
pState.setString(3, char1);
pState.setString(4, char2);
pState.setString(5, char3);
pState.setString(6, char3);
pState.executeUpdate();
pState.close();
incId();
}
catch (SQLException e){
System.err.println(e.getMessage());
}
}
private static void closeConnection() {
try {
// Close the connection
if(conn != null){
conn.close();
}
} catch(Exception e){
System.out.println(e.getMessage());
}
}
public static void queryShowAnimals() throws SQLException{
String query = "SELECT * FROM Animal";
try{
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(query);
while (rs.next()){
out.print(rs.getInt(nextId) + " ");
out.print(rs.getString("animalName") + " ");
out.print(rs.getString("char1") + ", ");
out.print(rs.getString("char2") + ", ");
out.print(rs.getString("char3") + ", ");
out.print(rs.getString("char4") + ", ");
}
}catch (SQLException se){}
}
public static void main(String[] args) throws ClassNotFoundException, SQLException {
AnimalDB1 db = new AnimalDB1();
AnimalDB1.createConnection();
System.out.println("Welcome to the Animal Database");
System.out.println("The list below shows all of the animals currently "
+ "stored in the database\n");
db.animalTable();
db.createAnimal("Huskie", "White", "Long hair", "Four legs", "Paws");
db.createAnimal("Salmon", "Silver", "Scales", "Fins", "Swims");
db.createAnimal("Crow", "Black", "Feathers", "Claws", "Flies");
db.createAnimal("Black Snake", "Black", "Scales", "No Appendages", "Slithers");
AnimalDB1.queryShowAnimals();
closeConnection();
}
}
There are two typing mistakes:
...
StringBuilder sb = new StringBuilder("");
sb.append("CREATE table Animal (\n");
sb.append("ID INTEGER NOT NULL,\n");
sb.append("AnimalName varchar(15),\n");
sb.append("Char1 varchar(15),\n");
sb.append("Char2 varchar(15),\n");
sb.append("Char3 varchar(15),\n");
sb.append("Char4 varchar(15)\n"); // <-- unnecessary comma
sb.append(")\n");
...
and:
...
while (rs.next()){
out.print(rs.getInt("ID") + " "); // <-- invalid column identifier
out.print(rs.getString("animalName") + " ");
out.print(rs.getString("char1") + ", ");
out.print(rs.getString("char2") + ", ");
out.print(rs.getString("char3") + ", ");
out.print(rs.getString("char4") + ", ");
}
...
Additionally, I believe that you want to use a database embedded. So, you need to load the corresponding driver (optional step since Java 6):
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
And the URL:
jdbc:derby:AnimalDB;create=true;user=test;password=test
Try using String buffer instead and i dont see the point in using \n after every line. Moreover chek u have proper spaces after each " .
StringBuffer sb = new StringBuffer("");
sb.append("CREATE table Animal ( ");
sb.append("ID INTEGER NOT NULL ");
sb.append("AnimalName varchar(15) ");
sb.append("Char1 varchar(15) ");
sb.append("Char2 varchar(15) ");
sb.append("Char3 varchar(15) ");
sb.append("Char4 varchar(15) ");
sb.append(" ) ");

NullPointerException in Java TableRowSorter

I made a jtable for the list of chemicals in the inventory where I can sort each columns using the following code (chemicalTable is the name of the jTable):
chemicalTable.setAutoCreateRowSorter(true);
TableRowSorter<TableModel> sorter1
= new TableRowSorter<TableModel>(chemicalTable.getModel());
chemicalTable.setRowSorter(sorter1);
Then I used a jTextfield to create a searchbox with a keyTyped Listener so that whenever the user types a certain character the table refreshes. And it usually works.
I used this code in the keyTypedListener for the searchbox:
DefaultTableModel dm = (DefaultTableModel) chemicalTable.getModel();
str = searchChemicalText.getText();
try {
String url = "jdbc:mysql://localhost/chemical inventory";
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, "root", "");
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error Occurred.", "Error", JOptionPane.ERROR_MESSAGE);
}
int ctr = 0;
while (ctr < chemicalTable.getRowCount()) {
chemicalTable.getModel().setValueAt(null, ctr, 0);
chemicalTable.getModel().setValueAt(null, ctr, 1);
chemicalTable.getModel().setValueAt(null, ctr, 2);
ctr++;
}
int count = 0;
try {
Statement stmt = conn.createStatement();
String query = "Select * FROM chemicallist where name_of_reagent like '%" + str + "%'";
ResultSet rs = stmt.executeQuery(query);
if (rs.next()) {
rs = stmt.executeQuery(query);
while (rs.next()) {
String qty = null, qtyunit = null, chemstate = null, reagentName = null;
reagentName = rs.getString("name_of_reagent");
qty = rs.getString("quantity");
qtyunit = rs.getString("quantity_unit");
chemstate = rs.getString("state");
chemicalTable.getModel().setValueAt(reagentName, count, 0);
chemicalTable.getModel().setValueAt(qty + " " + qtyunit, count, 1);
chemicalTable.getModel().setValueAt(chemstate, count, 2);
if (count + 1 > chemicalTable.getRowCount() - 1) {
dm.setRowCount(chemicalTable.getRowCount() + 1);
dm.fireTableRowsInserted(0, 5);
}
count++;
}
}
} catch (Exception e) {
JOptionPane.showMessageDialog(this, "Error Occurred.", "Error", JOptionPane.ERROR_MESSAGE);
}
My problem is: Whenever I sort first any columns (col1, col2, or col3) and I insert a character in the searchbox, I got this error message:
"Exception occurred during event dispatching:
Java.lang.NullPointerException"
Although it's not possible to debug your code fragments, several things stand out:
In the same section, you reference the TableModel as dm and chemicalTable.getModel(); use a single reference or verify that they refer to the same instance.
Instead of meddling with setRowCount(), use one of the addRow() methods.
The DefaultTableModel methods that alter the model fire the correct event for you and the table will automatically update itself accordingly; you shouldn't have to do this yourself.

Categories

Resources