The program have to download data from MySQL database. and fill the JList. I want to bind this data.
Here you have a code:
Connection connection = null;
String dbtime;
String query = "Select * FROM EMP";
String[] celDatas = null;
String[] celNames = null;
try {
(...)
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int NumOfCol = rsmd.getColumnCount();
celNames = new String[NumOfCol];
celDatas = new String[NumOfCol];
for(int weq=1; weq<=NumOfCol; weq++) {
System.out.println(rsmd.getColumnName(weq));
celNames[weq-1] = rsmd.getColumnName(weq);
while (rs.next()) {
dbtime = rs.getString(weq);
System.out.println(dbtime);
celDatas[weq-1] = dbtime;
}
rs = stmt.executeQuery(query);
System.out.println();
}
} catch (ClassNotFoundException e) {
} catch (SQLException e) {
}
final JList source = new JList(celDatas,celNames);
JScrollPane pane = new JScrollPane(source);
pane.setSize(f.getSize().width-60,300);
pane.setLocation(30,20);
I have a problem with
final JList source = new JList(celDatas,celNames);
It shows this problem in Netbeans: http://dl.dropbox.com/u/8455739/Java-Problem.png
//String[] celDatas = null;
String[][] celDatas = null;
String[] celNames = null;
...
//final JList source = new JList(celDatas,celNames);
final JTable source = new JTable(celDatas,celNames);
Related
I am having to connect an access database to a netbeans project and create a program that allows a user to search for a football player's name, and have their results displayed on the screen. My problem is that when I do the setTexts at the end, the labels simply turn blank. I do not receive any error messages.
I don't know whether the problem lies in the linking to the database or in parsing the parameters, or somewhere else?
Connection conn = null;
PreparedStatement pst = null;
ResultSet rst = null;
String temp = new String();
String playerID = null;
String name = null;
String surname = null;
String shirtNo = null;
String height = null;
String prefFoot = null;
String nation = null;
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
conn = DriverManager.getConnection("jdbc:ucanaccess://Database4.accdb");
String sql = "SELECT * FROM Players WHERE Name = (?) and Surname = (?)";
pst = conn.prepareStatement(sql);
pst.setString(1, txtfieldFirst.getText());
pst.setString(2, txtfieldSecond.getText());
rst = pst.executeQuery();
if(rst.next())
{
int count = 0;
while(rst.next())
{
playerID = rst.getString("PlayerID");
name = rst.getString("Name");
surname = rst.getString("Surname");
shirtNo = rst.getString("ShirtNo");
height = rst.getString("Height (Metres)");
prefFoot = rst.getString ("PrefFoot");
nation = rst.getString ("Nation");
}
}
conn.close();
}
catch (Exception e)
{
System.out.println(e);
}
Connection con = null;
PreparedStatement pstt = null;
ResultSet rs = null;
String temp2 = new String();
String league = null;
String DOB = null;
String club = null;
boolean tec = false;
String goals15 = null;
String goals16 = null;
String goals17 = null;
String assists15 = null;
String assists16 = null;
String assists17 = null;
try
{
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
con = DriverManager.getConnection("jdbc:ucanaccess://Database4.accdb");
String sqll = "SELECT * FROM Stats WHERE PlayerID = (?)";
pstt = con.prepareStatement(sqll);
pstt.setString(1, playerID);
rs = pstt.executeQuery();
if(rs.next())
{
int count = 0;
while(rs.next())
{
league = rs.getString("League");
DOB = rs.getString("DOB");
club = rs.getString("Club");
goals15 = rs.getString("Goals15/16");
goals16 = rs.getString("Goals16/17");
goals17 = rs.getString("Goals17/18");
assists15 = rs.getString("Assists15/16");
assists16 = rs.getString("Assists16/17");
assists17 = rs.getString("Assists17/18");
}
}
con.close();
}
catch (Exception e)
{
System.out.println(e);
}
babyStats pps = new babyStats(league, DOB, club, goals15, goals16, goals17, assists15, assists16, assists17);
babyPlayers ps = new babyPlayers(name, surname, shirtNo, height, prefFoot, nation);
PlayerScreen p = new PlayerScreen(ps, pps); //connection to other screen
p.setVisible(true);
this.setVisible(false);
public PlayerScreen(babyPlayers obj, babyStats objj) //parsed as paramters
{
initComponents();
lblName.setText(obj.getName());
lblSurname.setText(obj.getName());
lblShirtNo.setText(obj.getShirtNo());
lblDOB.setText(objj.getDOB());
lblHeight.setText(obj.getHeight());
lblPFoot.setText(obj.getPreFoot());
lblClub.setText(objj.getClub());
lblNation.setText(obj.getNation()); //these setTexts just make the labels blank
lblGoals16.setText(objj.getGoals1516());
lblGoals17.setText(objj.getGoals1617());
lblGoals18.setText(objj.getGoals1718());
lblAssists16.setText(objj.getAssists1516());
lblAssists17.setText (objj.getAssists1617());
lblAssists18.setText (objj.getAssists1718());
}
I expect the labels to be set with the details coming from the database, but they turn blank instead. I would really appreciate any help. *Update, while debugging, I used system.out.println to print one of the names, and the result came out as null. *Update, I fixed it, the while loops were not meant to be there.
I can't find the reason why this piece of code when run for a long time produces an out of memory heap error. It runs constantly for 1-2 days before crashing. Can anyone see anything?
I only call a static function from another class that should not keep any resources open and then the mysql stuff but I close them all.
note: some of the variable names were changed.
public class Application {
public static void main(String ...args) throws InterruptedException, IOException {
Data.connectDb(); //init
try {
List<Integer> written = new ArrayList<>();
Connection con = Data.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM table2 LIMIT 500");
while (rs.next()) {
Integer mId = rs.getInt("mId");
written.add(mId);
}
Map<Integer,String> bs = new HashMap<>();
rs = st.executeQuery("SELECT * FROM b");
while (rs.next()) {
bs.put(rs.getInt("bId"),rs.getString("name"));
}
st.close();
rs.close();
while (true) {
List<String> abers = new ArrayList<>();
st = con.createStatement();
rs = st.executeQuery("SELECT * FROM table1 WHERE enabled = 1");
while (rs.next()) {
String email = rs.getString("email");
abers.add(email);
}
rs.close();
st.close();
ArrayList<Map> abs = Aber.getAbs(false);
ArrayList<Map> toDispatch = new ArrayList<>();
arbs.forEach((ab) -> {
Integer mId = (Integer) ab.get("mId");
if (!written.contains(mId)) {
written.add(mId);
toDispatch.add(arb);
Pair hLine = (Pair) ab.get("hLine");
Pair dLine = (Pair) ab.get("dLine");
Pair aLine = (Pair) ab.get("aLine");
//todo write it to the database not caring if it's already there as we have a unique constraint
try (Statement st2 = con.createStatement()) {
String sql = "INSERT INTO table1")";
st2.executeUpdate(sql);
} catch (SQLException e) {
e.printStackTrace();
}
}
});
if (toDispatch.size() >0) {
Email email = new Email();
abes.forEach(arber -> email.addRecipient(aber, aber, Message.RecipientType.BCC));
String HTML = "<h3>Dear subscribers</h3>";
email.setTextHTML(HTML);
new Mailer(
new ServerConfig("mail.name.com", 587, "info#mm.com", "mmpass"),
TransportStrategy.SMTP_TLS
).sendMail(email);
}
Thread.sleep(600000);
}
} catch (SQLException sqle) {
System.out.println(sqle.getMessage());
}
}
}
Quick questions...
I'm trying to make a Dynamic JTree but I can't get to put every database I have into one single node for each one. This is my code so far:
jTree2 = new javax.swing.JTree();
try {
String DSN = "jdbc:mysql://localhost";
String user = "root";
String password = "";
conexion = DriverManager.getConnection(DSN, user, password);
}
catch(Exception e) {
System.out.println("ERROR");
}
try {
sentencia = conexion.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
}
catch(Exception e) {
System.out.println("ERROR2");
}
try {
String hi = "";
ResultSet rs1 = conexion.getMetaData().getCatalogs();
ResultSetMetaData rsmd = rs1.getMetaData();
int columnCount = rsmd.getColumnCount();
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++ ) {
hi = hi + rs1.getString(i) + ", ";
}
//for
String sb = hi.substring(0, hi.length()-2);
jTree2.setModel(new FileSystemModel(new File(sb)));
}
}
catch(Exception ae) {
System.out.println("ERROR3");
}
jScrollPane3.setViewportView(jTree2);
And the result I get is this:
Every database is splitted by a "," but I want them to be on a single node for each one. Any help?
This should do it for you:
DefaultMutableTreeNode parent = new DefaultMutableTreeNode("Databases", true);
while (rs1.next()) {
for (int i = 1; i <= columnCount; i++) {
DefaultMutableTreeNode node = new DefaultMutableTreeNode(rs1.getString(i), true);
parent.add(node);
}
jTree2.setModel(new DefaultTreeModel(parent));
}
Am trying to load the results of a database into a jtable, but when i run the code it only displays the first row and then errors an exception that no data was found. Here is my code;
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\Users\\PMatope.FMBMW.000\\Documents\\Library.accdb";
conn = DriverManager.getConnection(url, "", "");
st = conn.createStatement();
ResultSet rs = st.executeQuery("SELECT ID,full_name,sex,course,contact,email FROM Person");
ResultSetMetaData data = rs.getMetaData();
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
// jTable1.setModel(model);
while (rs.next()) {
String id,fname,sex,course,contact,email;
id = rs.getString("ID");
fname = rs.getString("full_name");
sex = rs.getString("sex");
course = rs.getString("course");
contact = rs.getString("contact");
email = rs.getString("email");
model.addRow(new Object[] {id,fname,sex,course,contact,email});
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, rs.getString("sex"));
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null,"Message: "+ e.getMessage());
}
Declare your table model first and create new instance for each loop times.
eg. :
DefaultTableModel model = null;
// jTable1.setModel(model);
while (rs.next()) {
model = (DefaultTableModel) jTable1.getModel();
String id,fname,sex,course,contact,email;
id = rs.getString("ID");
fname = rs.getString("full_name");
sex = rs.getString("sex");
course = rs.getString("course");
contact = rs.getString("contact");
email = rs.getString("email");
model.addRow(new Object[] {id,fname,sex,course,contact,email});
model.fireTableDataChanged();
JOptionPane.showMessageDialog(null, rs.getString("sex"));
}
You need to initialise,
DefaultTableModel model = (DefaultTableModel) jTable1.getModel();
inside your while loop
I'm writing java code that connects to a database in MySQL. I have a connection but I can't get the data to display in a label in my JFrame. So I'm connected to the database software in my XAMPP database but I can't get the data to display in the label
ResultSet rs;
ResultSetMetaData rsmd = null;
int colCount = 0;
String[] colNames = null;
try {
rs = engine.executeQuery("select * from music");
rsmd = rs.getMetaData();
colCount = rsmd.getColumnCount();
colNames = new String[colCount];
for (int i = 1; i <= colCount; i++) {
colNames[i - 1] = rsmd.getColumnName(i);
}
String[] currentRow = new String[colCount];// array to hold the
// row data
while (rs.next()) { // move the rs pointer on to the next record
// (starts before the 1st)
for (int i = 1; i <= colCount; i++) {
currentRow[i - 1] = rs.getString(i);
}
}
//System.out.println(authenticated);
}
catch (SQLException a)
{
System.err.println("SQLException: " + a.getMessage());
}
use this code its working
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.ResultSetMetaData;
public class Db {
public static void main(String arg[]) throws SQLException,
ClassNotFoundException {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(
"jdbc:mysql://localhost/dbname", "root", "");
java.sql.Statement stmt = conn.createStatement();
String query = "select * from music";
ResultSet rs = stmt.executeQuery(query);
ResultSetMetaData rsmd = rs.getMetaData();
int columncount = rsmd.getColumnCount();
for(int i = 1 ; i < columncount ; i ++)
System.out.print(rsmd.getColumnName(i));
System.out.println();
while (rs.next()) {
for(int i = 1 ; i < columncount ; i ++)
{
System.out.print(rs.getString(i));
}
System.out.println();
}
conn.close();
}
}
Since you want to have separate class for DB connection and use this connection somewhere else you could do something like this.
public class SQLConnect {
public static Connection ConnectDb() {
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/databasename", "root", "");
} catch (SQLException ex) {
Logger.getLogger(SQLConnect.class.getName()).log(Level.SEVERE, null, ex);
}
return conn;
}
catch (ClassNotFoundException e) {
System.out.println("not connected");
e.printStackTrace();//print extra info if error is thrown
return null;
}
}
}
And use this class as follows
Connection conn = null;
ResultSet rs = null;
PreparedStatement pst = null;
try {
conn = SQLConnect.ConnectDb();
String sql = "SELECT * FROM somedatabase WHERE somevalue = ? ";
pst = conn.prepareStatement(sql);
pst.setString(1, CriminalID);
rs = pst.executeQuery();
if(rs.next()) {
/*
* set values of labels to those from database
*/
jLabel.setText(rs.getString("Column name"));
}
this will get you data from database where some value is equal to whatever you specify