Displaying Database records to JTable in JAVA swing - mysql

I am trying to display the database records in the Jtable but i m not getting the code right. I m using IDE netbeans and database is mysql. I can see the panel and the scroll pane but the table is not displayed. I think something is wrong in the table properties or dont know if its invisible.
My code is as follows:
try{
panel_paylist.setVisible(true);
String dbUrl = "jdbc:mysql://localhost/hostel";
String dbClass = "com.mysql.jdbc.Driver";
Class.forName("com.mysql.jdbc.Driver");
Connection conn=DriverManager.getConnection(dbUrl,"root","17121990");
System.out.println("Connected!!!!");
MainScreen obj = new MainScreen(conn);
String[] columnNames = {"First Name",
"Last Name",
"Amount Recvd.",
"Date","Cheque/cash","cheque no","Balance Amt.","Total Amt.",
"Vegetarian"};
ResultSet rs = null;
Statement sql= null;
ArrayList<Object[]> data = new ArrayList<>();
String query="SELECT firstname,lastname, amountreceivd,dte,creditcashcheque,cheque_no,balance_amt, totalamount,Remark FROM payment;";
sql = con.createStatement();
sql.executeQuery(query);
rs = sql.getResultSet();
while(rs.next()){
Object[] row = new Object[]{rs.getString(1),
rs.getString(2),
rs.getInt(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getInt(7),
rs.getInt(8),
rs.getString(9)};
data.add(row);
}
Object[][] realData = data.toArray(new Object[data.size()][]);
table_paylist= new JTable(realData, columnNames);
scroll_paylist= new JScrollPane(table_paylist);
table_paylist.setPreferredScrollableViewportSize(new Dimension(800, 200));
table_paylist.setFillsViewportHeight(true);
panel_paylist.setLayout(new BorderLayout());
panel_paylist.add(scroll_paylist, BorderLayout.CENTER);
}
catch(Exception e)
{
}
please help

first of all you are missing port number of localhost.
change
"jdbc:mysql://localhost/hostel"
to
"jdbc:mysql://localhost:3306/hostel";
second point dont use semicolon(;) at the end of sql string. i. e. remove semicolon from
"SELECT firstname,lastname, amountreceivd,dte,creditcashcheque,cheque_no,balance_amt, totalamount,Remark FROM payment;"
and you can also try this one
public DefaultTableModel PlayList() throws ClassNotFoundException,SQLException,ParseException
{
String[] columnNames = {"First Name","Last Name","Amount Recvd.","Date","Cheque/cash","cheque no","Balance Amt.","Total Amt.","Vegetarian"};
DefaultTableModel dtm = new DefaultTableModel(columnNames , 0);
dtm.setColumnCount(9);
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:8080/hostel","root","17121990");
PreparedStatement ps1 = null;
ResultSet rs1 = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
ps1=conn.prepareStatement("SELECT firstname,lastname,mountreceivd,dte,creditcashcheque,cheque_no,balance_amt,totalamount,Remark FROM payment");
rs1 = ps1.executeQuery();
while(rs1.next())
{
dtm.addRow(new Object[]{rs1.getString(1)
rs.getString(2),
rs.getInt(3),
rs.getString(4),
rs.getString(5),
rs.getString(6),
rs.getInt(7),
rs.getInt(8),
rs.getString(9)});
}
}
finally
{
rs1.close();
ps1.close();
conn.close();
}
return dtm;
}
now use PlayList() method as a argument of your jtable's setmodel method;
i. e. jtable.setmodel(PlayList());

Use rs2xml third party Jar file to display query results.This is very helpful

Related

How can refresh a ResultSet in Java

I want to use a MySQL with JDBC in a loop, because I have to poll a table frequently for new data which comes in from other clients. But even if I close the ResultSet, the connection and the statement, is the old result at the next round still there. I cannot get a new result, unless I restart the program. What is my mistake?
I condensed the code for the necessary.
import java.sql.*;
public class Eventmgr {private static String in_text;
private static String in_typ;
private static Connection connection;
private static String URL = "jdbc:mysql://xxx.xxx.x.x:3306/xxxx";
private static String username = "xxx";
private static String password = "xxx";
public static void start() throws SQLException {
while(loop_count > 0) {
if (loop == false) {
loop_count = loop_count -1;}
connection = DriverManager.getConnection(URL, username, password);
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("select id, nummer, text, typ from inbox order by id asc limit 1") ;
while(rs.next()) {
in_id = rs.getString("id");
in_nummer = rs.getString("nummer");
in_text = rs.getString("text");
in_typ = rs.getString("typ");}
connection.close();
stmt.close();
rs.close();
System.out.println("still running");
}
}
}
Anybody has an idea what my problem is?
Thanks in advance
I am stupid, and it was my mistake...
The problem is. I check on the variable "in_id" and if there is no new result "while(rs.next())" dont deliver a new value, so I need to reset that variable with "in_id = null;" at the end of the loop.
Now it works...

Does h2 have a query/clause similar to the WHERE IN in MySQL?

My code currently goes as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
String[] data = parentIds.toArray(new String[parentIds.size()]);
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (?)";
stmt = conn.prepareStatement(sql);
data = parentIds.toArray(data);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
However even though in the unit tests I try to pass an array with parentIds, the return remains null.
What I can gauge from this is one of the following:
The array data isn't getting properly read, therefore the output is coming as null.
WHERE IN is not supported by h2 or else there is a different implementation that needs to be used instead.
Where am I going wrong in this?
EDIT - There was a similar duplicate question that was tagged. While it suggested using a StringBuilder and a loop, I was looking for an answer stating how it could be done in a cleaner way using the query itself.
Try setting the parameter as a list instead of an array, ie replace
stmt.setObject(1, data);
with
stmt.setObject(1, Arrays.asList(data));
Figured it out.
There was an issue posted on the h2database GitHub about this exact problem. Followed the suggested edits and it worked!
Code after edits is as follows:
public List<DeviceOrganizationMetadataHolder> getChildrenByParentId(List<String> parentIds) throws DeviceOrganizationDAOException {
List<DeviceOrganizationMetadataHolder> children = new ArrayList<>();
Connection conn;
PreparedStatement stmt = null;
ResultSet rs = null;
DeviceOrganizationMetadataHolder deviceMetadataHolder;
Object[] data = parentIds.toArray();
try {
conn = this.getConnection();
String sql = "SELECT * FROM DEVICE_ORGANIZATION_MAP WHERE DEVICE_PARENT IN (SELECT * FROM TABLE(x VARCHAR = ?))";
stmt = conn.prepareStatement(sql);
stmt.setObject(1, data);
rs = stmt.executeQuery();
while (rs.next()) {
deviceMetadataHolder = this.loadOrganization(rs);
children.add(deviceMetadataHolder);
}
} catch (SQLException e) {
throw new DeviceOrganizationDAOException("Error occurred for device list with while retrieving children.", e);
} finally {
DeviceManagementDAOUtil.cleanupResources(stmt, rs);
return children;
}
}
As you can see, I've used an Object array for data instead and added an additional query inside the main query.
Followed the instructions given in the GitHub issue to a tee and it worked flawlessly.

How to get data from database javafx

I have this project and I need to get data (writing) from a database and I am using javaFX. I have a connection class that works (when I run it makes the connection)
public class Conexiune extends JPanel {
public Connection con = null;
public Statement stmt = null;
public ResultSet rs = null;
Vector data = null;
Vector columns = null;
JTable table;
JPanel paneOrar;
JTable tabel;
void login() throws SQLException {
String url = "jdbc:mysql://localhost:3308/database";
String login = "root";
String password = "password";
con = (Connection) DriverManager.getConnection(url, login, password);
}
Component query() throws SQLException {
stmt = con.createStatement();
ResultSet result = stmt.executeQuery("SELECT * FROM data");
ResultSetMetaData md = (ResultSetMetaData) result.getMetaData();
int columnCount = md.getColumnCount();
Vector columns = new Vector(columnCount);
// store column names
for (int i = 1; i <= columnCount; i++)
columns.add(md.getColumnName(i));
Vector data = new Vector();
Vector row;
// store row data
while (result.next()) {
row = new Vector(columnCount);
for (int i = 1; i <= columnCount; i++) {
row.add(result.getString(i));
}
data.add(row);
}
JScrollPane scrollPane = new JScrollPane(tabel);
this.setLayout(null);
JTable table = new JTable(data, columns);
return this.add(table);
}
Conexiune() {
try {
login();
System.out.println("bdConnect");
} catch (SQLException sqle) {
System.err.println(sqle);
}
}
}
After I run I get the message bdConnect with no errors.
The main problem is that i don't know what to do after, I mean I want to get the text from the database on to something that is not a table. Something like a scrollPane. Lets say i just want a window full of text on multiple lines but not a table. Lets say that you want to get the contents of a book from your database, you cant put it in a table. Can anyone help me please I'm getting kind of desperate!!!

Stored images(Longblob) in my database and I can't display it into a jlabel

I'm trying to display images from database into jlabel
IMAGES = column name, currentuser.getText() = i have a text on the top which determines the column USERNAME in my database
EDITED - I really dunno what to do anymore, it's been a week but still i cant display the image from the database
public class MyProfile extends JFrame implements ActionListener{
Container c;
ResultSet rs;
Connection con;
Statement st;
TempData temp = new TempData(); //Class for storing current user who logins (Set & get)
JLabel currentuser = new JLabel("" + temp.getUsername());
JLabel displayPhoto = new JLabel();
public MyProfile() {
super("My Profile");
this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
this.setSize(1175, 698);
this.setLocationRelativeTo(null);
this.setVisible(true)
c = this.getContentPane();
c.setLayout(null);
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost/pancakefinder", "root", "");
st = con.createStatement();
} catch (Exception exp) {
}
c.add(currentuser);
currentuser.setFont(new Font("Times New Roman", Font.PLAIN, 20));
currentuser.setForeground(Color.orange);
c.add(displayPhoto);
displayPhoto.setBounds(160, 330, 250, 230);
displayPhoto();
}
public void displayPhoto() {
try {
PreparedStatement pst = null;
rs = null;
pst = con.prepareStatement("select IMAGES from images where USERNAME = '" + currentuser.getText() + "'");
rs = pst.executeQuery();
byte[] bytes = null;
if (rs.next()) {
bytes = rs.getBytes("images");
Image img = Toolkit.getDefaultToolkit().createImage(bytes);
displayPhoto.setIcon(new ImageIcon((img)));
displayPanel.add(displayPhoto);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void main(Stringp[] args){
MyProfile ex = new MyProfile();
}
}
I'm guessing that displayPanel is a JPanel and displayPhoto is the JLabel. If displayPhoto was added before pack(), setIcon() should be enough. If not, you'll need to revalidate() the panel after add(). Also check if the rs.next() result is false, and remember that it will only fetch one row; you'll need a loop to get any other rows.

Access import into SQL server not importing first line

I am using a function to import data from a access db into SQL server:
public string importDataFromAccess(string table, string fileName)
{
OleDbConnection OleDbConn = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
try
{
string sSQLTable = table;
string myExcelDataQuery = "Select * from " + sSQLTable;
string sSqlConnectionString = connStr;
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
return "Done";
}
catch (Exception ex)
{
OleDbConn.Close();
return ex.ToString();
}
}
I noticed it isnt importing the first record of each table, can anyone help notice why and how to fix? Hopefully it is only the first row...
You shouldn't need the
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
And you just need to replace that with
bulkCopy.WriteToServer(dr);
The WriteToServer method
Copies all rows in the supplied IDataReader to a destination table
specified by the DestinationTableName property of the SqlBulkCopy
object.
But the dr.Read() that you have called has read the first line out of the Reader and advanced the IDataReader to the next record (so it is not accessible to the WriteServer method).