I'm trying to user mouse event to display the selected row from jtable in other text field but when i run it and clicked on any row it's coming with this message java.sql.Exception [microsoft ][odbc microsoft access drive] data type mismatch in criteria exception
please any idea can help
this is the code :
private void jTable1MouseClicked(java.awt.event.MouseEvent evt) {
try
{
int row = jTable1.getSelectedRow();
String Table_Click = (jTable1.getModel().getValueAt(row,0).toString());
String Sql= "SELECT * FROM tblUsers WHERE ID='" + Table_Click +"' ";
pst = con.prepareStatement(Sql);
rs = pst.executeQuery();
if(rs.next())
{
String Add1= rs.getString("ID");
jTextField_ID.setText(Add1);
String AddBrNa= rs.getString("UserName");
jTextField_UN.setText(AddBrNa);
String AddBrAdd= rs.getString("Password");
jPasswordField_Pass.setText(AddBrAdd);
String AddBrYear= rs.getString("FName");
jTextField_FN.setText(AddBrYear);
String AddBrCourse= rs.getString("LName");
jTextField_LN.setText(AddBrCourse);
String AddBrSec= rs.getString("DateCreated");
jTextField_date.setText(AddBrSec);
JOptionPane.showMessageDialog(null, "errorif");
}
else
{
JOptionPane.showMessageDialog(null, "error");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
I'm trying to user mouse event to display the selected row from jtable
in other text field
There's no need to use MouseListener to do that. Just implement a ListSelectionListener instead, that will be executed even if the selection change is made through keyboard or code:
jTable1.getSelectionModel().addListSelectionListener(new ListSelectionListener() {
#Override
public void valueChanged(ListSelectionEvent e) {
// Your code here
}
};
If you still want to use MouseListener then I'd suggest you make this change:
//int row = jTable1.getSelectedRow();
int row = jTable1.rowAtPoint(evt.getPoint());
Because you can't be sure the row selection will change before this event is triggered. I'm not sure but I would say a MouseEvent should have precedence over a ListSelectionEvent.
However be aware thisrow index belongs to the view, not the model, so the following line may not return the expected result if your table is a sorted one:
String Table_Click = (jTable1.getModel().getValueAt(row,0).toString());
It should be:
String Table_Click = (jTable1.getValueAt(row,0).toString());
Having said this, the proper use of PreparedStatemen is the one #camickr just pointed out:
String sql = "SELECT * FROM tblUsers WHERE ID = ?";
PreparedStatement pst = con.prepareStatement(sql); //
pst.setString(1, Table_Click) // assuming the ID is a varchar, since you enclosed it into ''
Also be aware that you're accessing your database in the Event Dispatch Thread. You should do that in a separate thread and update Swing components in the EDT. SwingWorker sounds like a good match in this case.
java.sql.Exception [microsoft ][odbc microsoft access drive] data type mismatch in criteria exception: is nothing to do with your table. Check your SQL query. Most likely your ID is an integer type but you are checking it as string, inside your where clause:
WHERE ID='" + Table_Click +"'
Try using a PreparedStatement to make the SQL easier. If you do need to use an int as suggested by Sage then you can do:
String sql = "SELECT * FROM tblUsers WHERE ID = ?";
PreparedStatement pst = con.prepareStatement(sql);
pst.setInt(1, ...)
thanks all,
this is working fine:
String Sql= "SELECT * FROM tblUsers WHERE ID=" + Table_Click;
Related
I want to find user by ID entered into a textfield, If the ID is not found I would like to display "User Not Found".
This is what I have so far, but it is only displaying an error if the entered textfield is greater than MAX id in the table:
Statement stmt7 = connection.createStatement();
String query2 = "SELECT MAX(empid) AS MaxId FROM employee";
ResultSet rs2 = stmt7.executeQuery(query2);
while(rs2.next())
{
if(Integer.parseInt(searchEmployeeFld.getText()) > rs2.getInt("MaxId"))
{
// create a alert
Alert a = new Alert(AlertType.NONE);
// set alert type
a.setAlertType(AlertType.ERROR);
// set content text
a.setContentText("User Not Found");
// show the dialog
a.show();
}
else
{
Statement stmt6 = connection.createStatement();
System.out.println("Executing a Query...");
String query = "SELECT empname, empgrsal "
+ "FROM employee WHERE empid = " + searchEmployeeFld.getText();
ResultSet rs1 = stmt6.executeQuery(query);
while(rs1.next())
{
NameFld.setText(rs1.getString("empname"));
String test1 = Double.toString(rs1.getDouble("empgrsal"));
grossSalaryFld.setText(test1);
// calculate net salary
double grossSal = rs1.getDouble("empgrsal");
grossSal -= (grossSal * 0.3);
String test2 = Double.toString(grossSal);
netSalaryFld.setText(test2);
}
rs1.close();
}
}
rs2.close();
Here is a modified and annotated version of your code that should do what you are looking for.
// Use a prepared statement, with a ? in the place of empid
// This will protect from SQL injection attacks, and more, it will
// prevent your database SGA from getting choked full of thousands of
// similar SQL statements. This is much more efficient from a DB perspective.
String query = "SELECT empname, empgrsal FROM employee WHERE empid = ?";
// A flag to see if we got the user
boolean found = false;
// Using "try with resources" makes life much easier
try (PreparedStatement ps1 = connection.prepareStatement(query)){
// You have to set the value for the "?" in the SQL statement.
// If an employee ID is a number, then you really should convert
// the text to a number and use "setLong" instead of "setString"
ps1.setString(1,searchEmployeeFld.getText());
try(ResultSet rs1 = ps1.executeQuery()){
// No need to loop. Your code is designed to find one user by key.
if(rs1.next()){
found = true;
NameFld.setText(rs1.getString("empname"));
String test1 = Double.toString(rs1.getDouble("empgrsal"));
grossSalaryFld.setText(test1);
// calculate net salary
double grossSal = rs1.getDouble("empgrsal");
grossSal -= (grossSal * 0.3);
String test2 = Double.toString(grossSal);
netSalaryFld.setText(test2);
}
}
} // Should catch SQLException somewhere and do something about it
if(!found){
// Didn't find the ID...do something about it
}
A few more notes...
You are (probably) executing SQL within the Swing GUI thread, which is not optimal. For fast queries it's not so bad, but any delay will be felt by the user as a frozen UI. And if you aren't in the GUI thread there are other concerns (calls to Swing objects should be in the GUI thread).
The "try with resources" technique will automatically close the prepared statement and result set.
image showing my jFrame
I am making a frame which shows records in the sql table one-by-one using text fields as shown. While writing the code for the next button, I need to know the position of the result set to go to the next record. For this purpose, I used a do-while loop with an "if" condition. Following is my code:
try{
Connection conn=null;
Statement stmt=null;
ResultSet rs=null;
String url="jdbc:mysql://localhost/MYORG", userid="root", pwd="shreyansh";
conn=DriverManager.getConnection(url,userid,pwd);
stmt=conn.createStatement();
String query="select * from emp;";
rs=stmt.executeQuery(query);
String search=jTextField1.getText();
String search1=jTextField2.getText();
double search2=Double.parseDouble(jTextField3.getText());
String search3=jTextField3.getText();
rs.first();
do{
if(rs.equals(new Object[] {search, search1, search2, search3}))
break;
}while(rs.next());
rs.next();
String nm=rs.getString("Name");
String desg=rs.getString("Designation");
double pay=rs.getDouble("Pay");
String city=rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(pay + "");
jTextField4.setText(city);
}catch(Exception e){
JOptionPane.showMessageDialog(null, e.getMessage());
}
But it shows an error "after end of Result Set".
Please help me with this.
Any suggestions to make my code better are also welcome.
Thanks in Advance!!
You can't use ResultSet.equals for this, because that is not what the Object.equals contract is for. It is for checking if an object is equal to another object of the same (or at least compatible) type. A ResultSet will therefor never be equal to an array of object values.
It looks like you want to select a single row from the emp table that matches your search values, in that case the correct solution is to ask the database for only that row. Selecting all rows and then filtering in your Java application is very inefficient, because the database has to send all rows to your application, while finding data is exactly what a database is good at.
Instead, you should use a where clause with a prepared statement:
try (Connection connection = DriverManager.getConnection(url, userid, pwd);
PreparedStatement pstmt = connection.prepareStatement(
"select * from emp where Name = ? and Designation = ? and Pay = ? and City = ?")) {
pstmt.setString(1, search);
pstmt.setString(2, search1);
pstmt.setDouble(3, search2);
pstmt.setString(4, search3);
try (ResultSet rs = pstmt.executeQuery()) {
if (rs.next() {
String nm = rs.getString("Name");
String desg = rs.getString("Designation");
double pay = rs.getDouble("Pay");
String city = rs.getString("City");
jTextField1.setText(nm);
jTextField2.setText(desg);
jTextField3.setText(String.valueOf(pay));
jTextField4.setText(city);
} else {
// handle not found case
}
}
}
I'm trying to show search result from mysql table through a jtextfield, but after I clicked the button it doesn't show in jtable I wonder why, please help me to solve this error, thanks :)
Button Code on MouseCLicked :
private void btn_cariMouseClicked(java.awt.event.MouseEvent evt) {
if(!inp_npm.getText().isEmpty()){
show_item_in_searchTbl();
} else {
JOptionPane.showMessageDialog(null, "Please fill the empty text!");
}
}
public void show_item_in_searchTbl(){
try{
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/zazu_school","root","");
Statement st = conn.createStatement();
String query = "SELECT NPM FROM daftar_mahasiswa WHERE NPM LIKE '%" + inp_npm.getText() + "%'";
ResultSet rs;
rs = st.executeQuery(query);
DefaultTableModel model = (DefaultTableModel)src_mhs_tbl.getModel();
while(rs.next()){
Object[] kolom = new Object[3];
kolom[0] = rs.getInt("ID");;
kolom[1] = rs.getString("Nama");
kolom[2] = rs.getString("NPM");
kolom[3] = rs.getString("Jurusan");
model.addRow(kolom);
}
conn.close();
} catch(SQLException ex){
}
}
the image of the program
Welcome to StackOverflow :)
The error is happening when you call the following :
kolom[0] = rs.getInt("ID");
However, your Select statement is :
String query = "SELECT NPM FROM daftar_mahasiswa WHERE NPM LIKE '%" + inp_npm.getText() + "%'";
ie. your getInt is attempting to get a value for a column that was never selected, so is not in the ResultSet.
The defined behaviour for getInt is to therefore throw a SQLException, which you catch but don't log it or anything.
Solution is to :
1) modify your SELECT to retrieve all the columns
2) Add some logging, etc to properly handle SQLException
3) The clause '%" + inp_npm.getText() + "%'" is opening your Select statement to SQL Injection attacks, so instead generate your statement using PreparedStatement.
My Jtable is connected to the database that I made so that it can show all the data right in my GUI. But Im trying to fetch the data from my JTable to the JTextField. Its like when you click the row of the table the data from the database thats inside the table will go to the TextField. But when I clicked the table it shows an error like this:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an
error in your SQL syntax; check the manual that corresponds to your
MariaDB server version for the right syntax to use near 'NO.='1
RASCHEL" at line 1
I've been searching for the answer but I was unable to find one. Please help me I've been stuck to this error since friday.
table = new JTable();
scrollPane.setViewportView(table);
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
int row = table.getSelectedRow();
String table_click = (table.getModel().getValueAt(row, 0).toString());
try {
String query = "SELECT * FROM `raschel` where MACHINE NO.='" + table_click + "'";
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
PreparedStatement ps = con.prepareStatement(query);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
String machine = rs.getString("MACHINE NO.");
String type = rs.getString("TYPE");
String product = rs.getString("PRODUCT");
txtMachine.setText(machine);
txtType.setText(type);
txtProd.setText(product);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
}
}
});
The column you are using MACHINE NO. contains a space and a dot in the end to work with like names you have to put the name between two :
`MACHINE NO.`
So your query should look like this :
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='" + table_click + "'";
But this still not secure agains syntax error or SQL Injection so instead you can use :
String query = "SELECT * FROM `raschel` where `MACHINE NO.` = ?";
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root","");
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, table_click);//<<-----------set the parameter like this
ResultSet rs = ps.executeQuery();
You sould not use blanks and dots in column names. If you have to use blank and dot you have to escape the column name with a backtick:
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='"+table_click+"'";
But i would strongly recommand to not use blanks and dots (or other special character) in column or table names.
String query = "SELECT * FROM `raschel` where MACHINENO='"+table_click+"'";
Also change to prepared statements to prevent SQL injection
Try this on your
String query = "SELECT * FROM `raschel` where `MACHINE NO.`='"+table_click+"'";
I have DDBB with a table users and I'm trying to get fields user_id and user_pass by searching for user_name.
So, when I run the following query:
SELECT `user_id`, `user_pass` FROM `users` WHERE `user_name` LIKE '%aName%';
It returns, ie aName = "John":
+---------+-----------+
| user_id | user_pass |
+---------+-----------+
| 5 | "1234" |
+---------+-----------+
Ok, then I want to perform this using a PreparedStatement, for that reason I have made this function:
private final String QUERY_GETUSERNAME2 =
"SELECT `user_id`, `user_fname`"
+ " FROM `users`"
+ " WHERE `user_fname` LIKE ?;";
private String[][] getUsersInv(String usrName){
ArrayList<String[]> alAux = new ArrayList();
String[][] ret = null;
try{
PreparedStatement st = _conn.prepareStatement(QUERY_GETUSERNAME2);
st.setString(1, "'%"+usrName+"%'");
ResultSet rs = st.executeQuery();
while(rs.next()){
String[] asAux = {String.valueOf(rs.getInt(1)), rs.getString(2)};
alAux.add(asAux);
}//while
}catch(SQLException e){
e.printStackTrace(System.out);
}finally{
if (!alAux.isEmpty()){
ret = new String[alAux.size()][alAux.get(0).length];
for (int i = 0; i < alAux.size(); i++)
ret[i] = alAux.get(i);
}//fi
}
return ret;
}
As you can see, the function returns a String[][], so I check in a previous function if returns is or not null:
public void insertUsersInvTableModel(JTable table, String user){
DefaultTableModel model = (DefaultTableModel) table.getModel();
String[][] row = getUsersInv(user);
if (row != null)
model.addRow(row);
}
And this function is call from the listener for a JButton:
private void addUserActionPerformed(java.awt.event.ActionEvent evt) {
if (comboUsers.getSelectedIndex() != 0){
new Users(_conn).insertUsersInvTableModel(_target, String.valueOf(comboUsers.getSelectedItem()));
_target.validate();
_target.repaint();
setVisible(false);
}
}
As you can imagine, there's a JDialog with a JComboBox with all the users listed down.
As table users is AUTO_INCREMENT, the user_id has some gaps (or maybe it will have), and the only way to build the JComboBox was without relate user_id to JComboBox index.
But, the problem is that whenever I pick an item from the JComboBox, and I run the process to get the user_id and user_pass based on the item selected (nor the index), the ResultSet is always NULL.
Any idea?
Thanks.
replace
st.setString(1, "'%"+usrName+"%'");
with
st.setString(1, "%"+usrName+"%");
The single quotes are automatically added by the PreparedStatement. With the Quotes the query will look for the String '%usrname%' instead of %usrname%
try
st.setString(1, "%"+usrName+"%");
instead of
st.setString(1, "'%"+usrName+"%'");
SOLUTION
As Marco Forberg pointed, quotes used for envolve the string parameter (') are not compulsory. Removing them fix the issue.