Jtable selected row in netbeans that is bounded to sql server - java

I fill a jtable(tbl_student) in netbeans by this code:
String[][] result;
result = stu.Search(txt_search.getText());
String hdr[] = {"code", "name", "family"};
tbl_student = new JTable(result, hdr);
jScrollPane1.setViewportView(tbl_student);
tbl_student.setComponentOrientation(ComponentOrientation.RIGHT_TO_LEFT);
That Search() function is a select all query from a table in sql server database.
Now, I want to find selected row in this table. How can I do it?
My code in mouse click event of this jtable is not work!
What can I do?

If you need to get some data when you clicked a row in a JTable use the following code.
int row=tbl_student.getSelectedRow();
String Table_data=(tbl_student.getModel().getValueAt(row, 0).toString()); // In here 0 means the column number.
//If you have a JTable with 5 columns; 0 is the 1st column and 4 is the last (5th) column.
If you want to get data in a database table to a JTable, their is a library called rs2xml.jar with the help of that library you can simply fill a JTable with database data.
You can download that library from HERE.
After downloading library use the following code to fill your JTable.
Connection conn=null;
ResultSet rs=null;
PreparedStatement pst=null;
try{
String sql="SELECT * FROM table_name"
conn=java_connect.ConnecrDb(); //Database connecting class
pst=conn.prepareStatement(sql);
rs=pst.executeQuery();
tbl_student.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
finally{
try{
rs.close();
pst.close();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}

Related

Java Application script to display the number of rows in a column, of a SQL table. Error in SQL query. The output should be in a label

Hello there. I am trying to get the result of my SQL query into a label on my java application. Any advice on what I am doing wrong? (The label is "lblTest", the table is "transactions" and the column in "TRANS_ID"). Thank you in advance.
try
{
conMySQLConnectionString =
DriverManager.getConnection
(strDBConnectionString,strDBUser,strDBPassword);
stStatement = conMySQLConnectionString.createStatement();
String strQuery = "SELECT COUNT(TRANS_ID)"+"FROM transactions";
stStatement.execute(strQuery);
rs = stStatement.getResultSet();
lblTest.setText(rs.getString(1));
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null,e);
}
}
You have to check if the resultSet contains at least one record :
if(rs.first()){
lblTest.setText(rs.getString(1));
}

How to achieve multiple combinations of JCombobox in java

I have 4 comboboxes...client.sengg,month,product and 1 JTable...so when I select any item from client want to display row in Jtable which contains these selected item..if I select sengg and product then values against this items want to display...if select client,month,product then these values should be displays...so currently only client is displays, So how to achieve it?
try
{
String query="Select * from enquiry where `client` =? or `Sales`=? or `month`=? or `Product`= ? " ;
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1,(String) client.getSelectedItem());
pst.setString(2,(String) sengg.getSelectedItem());
pst.setString(3,(String) product.getSelectedItem());
pst.setString(4,(String) month.getSelectedItem());
ResultSet rs=pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
//return;
}
catch(Exception e)
{
e.printStackTrace();
}
Or query is right for it?

mySQL showing null in images field

when I try to insert an image in MySQL database it shows:
Query OK, 1 row affected (0.06 sec)
but when I try to view it in net beans it tells that the field is null.
Also in MySQL when I put the query to display the field it shows null under the image column.
The strangest thing is that it happens only for some images and other images get added to the database and are displayed by the java net beans.
The table creation query is:
create table rto(sno int(2), image longblob);
the query to insert image in table is:
insert into rto values(2, LOAD_FILE('I:\WP_20150925_004.jpg'));
The java code is:
JFileChooser chooser=new JFileChooser();
chooser.showOpenDialog(null);
File f=chooser.getSelectedFile();
String filename=f.getAbsolutePath();
System.out.println(filename);
{
try{ int r= Integer.parseInt(jt2.getText());
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/darshanproject","root","");
Statement st = con.createStatement();
String q = "Insert into rto values("+r+",LOAD_FILE('"+filename+"'));" ;
int rs = st.executeUpdate(q);
if (rs>0)
System.out.println("image inserted");
else
System.out.println("not inserted");
}catch(Exception ex){
System.out.println(ex);
}
}
// TODO add your handling code here:
}
Please help me out.

Updating JTable when selecting item in combobox in Java

I coded auto suggesting comboBox that retrieve data from SQL database.It was successful.
Then as next step, I want these functionalities to be done,
*When user select a "ItemID" from the comboBox(When the user type first letter of ItemID, suggest list comes and user can select aItemID - successfully coded), JTable's "ItemID" column and other columns that related to that specific "ItemID" must be updated from the database.
I coded updateTable()method as below;
private void updateTable(){
String existID = (String) IDcombo.getSelectedItem();
String sql = "select * from druginfo WHERE ItemId LIKE '"+existID+"%'";
try {
PreparedStatement pst = conn.prepareStatement(sql);
ResultSet rs = pst.executeQuery();
saleTable.setModel(DbUtils.resultSetToTableModel(rs));
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex);
} }
Well your tablemodel needs to fire according to the event. If only table data changes then it should fire fireTableDataChanged(). If data and structure both changes then it should fire fireTableStructureChanged(). You can refer to the document
If you're still having trouble with this the one way is to call repaint on your table but that's not a very good way of doing things.

How To get All Rows in Mysql Database (Java)

So Sorry if this Looks newbie Question, Im not Skilled in Mysql, I need to Get Entries of All Rows in My Mysql Database like We Do with Sqlite in Android :
Cursor mCursor = mDb.query("MyTable",new String[]{"My Column"},null,null.null,null);
ArrayList<> mylist = new ArrayList<>();
do{
mylist.add(mCursor.getString(mCursor.getColumnIndex("_id")));
while(mCursor.moveToNext());
How does This Work in Mysql Guys?
first you have to create connection to your database, You can use JDBC for it.
Connection con=null;
PreparedStatement ps=null;
ResultSet rs=null;
public Dbconnection()
{
try{
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/databasename","root","root");
}
catch(Exception e)
{
System.out.println("Error in connection"+e);
}
}
connection created in the constructor,
method to get all rows from a table
public void getData()
{
try{
ps=con.prepareStatement("select * from tbl_name");
rs=ps.executeQuery();
while(rs.next())
{
System.out.println(rs.getString(1)); //here you can get data, the '1' indicates column number based on your query
}
}
catch(Exception e)
{
System.out.println("Error in getData"+e);
}
}
In the while loop you can all data from rs using rs.getString(1)
NB: change column number for different column.
To get more idea please refer the links:
http://www.tutorialspoint.com/jdbc/index.htm
http://www.w3schools.com/sql/

Categories