So at the moment I have a class called MySqlConnection with this code inside it
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.PreparedStatement;
import java.sql.Connection;
public class MySqlConnection {
public static void Connection() throws Exception {
// Accessing driver from the JAR file
Class.forName("com.mysql.jdbc.Driver");
// Creating a variable for the connection called "con"
Connection con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/Friends", "John", "John123");
// jdbc:mysql://localhost:3306/employee_record --> This is the database
// root is the database user
// root is the password
// Here we create our query
PreparedStatement Statement = con
.prepareStatement("SELECT * FROM names ORDER BY first");
// Creating a variable to execute query
ResultSet result = Statement.executeQuery();
while (result.next()) {
System.out.println(result.getString(1) + " " + result.getString(2));
}
}
}
When I run this, it displays all the results at once in the Eclipse IDE.
http://i.imgur.com/V9kA5fN.png
How do I make it display all the results in a separate window?
You can use JTable on the JFrame to show the data in tabular format on a window. You can find examples on Internet about using JTable.
You can use JTable. Here is my version
public class JResultTable extends JTable {
public DefaultTableModel dataModel;
ResultSet rs;
public void init_model(){
dataModel=new DefaultTableModel();
}
public void add_data() throws SQLException {
String colNames[];
ResultSetMetaData rsMetaData=rs.getMetaData();
int colCount=rsMetaData.getColumnCount();
colNames=new String[colCount];
for(int i=1;i<=colCount;i++)
colNames[i-1]=rsMetaData.getColumnName(i).toUpperCase();
dataModel.setColumnIdentifiers(colNames);
while(rs.next())
{
String[] rowdata= new String[colCount];
for(int i=1;i<=colCount;i++)
rowdata[i-1]=rs.getString(i);
dataModel.addRow(rowdata);
}
}
JResultTable(ResultSet rs) throws SQLException {
super();
init_model();
this.rs=rs;
add_data();
setModel(dataModel);
}
}
Ex- JResultTable mm=new JResultTable(rs)// rs is the resultset. Column Names will automatically become table headers (ResultSetMetaData)
add this mm to a panel or frame.
Related
My SQL connection keeps saying it's busy even though all previous connections are closed.
The error below results. All others are either closed by the exiting of the JFrame or the .close() method. Does anyone see anything wrong with the class? (All other classes work as intended.)
SEVERE: null
org.sqlite.SQLiteException: [SQLITE_BUSY] The database file is locked (database is locked)
at org.sqlite.core.DB.newSQLException(DB.java:941)
at org.sqlite.core.DB.newSQLException(DB.java:953)
at org.sqlite.core.DB.execute(DB.java:854)
at org.sqlite.core.DB.executeUpdate(DB.java:895)
package teacherreviewproject;
//initialise imports
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
public class FeedbackForm extends javax.swing.JFrame {
//init. variables
String WWW;
String EBI;
int rating;
String teacher;
String studentUser;
String ratingraw;
String teacherQuery;
public FeedbackForm(String s) {
initComponents();
getTeachersNames();
this.studentUser = s;
}
private void getTeachersNames(){
//get the connection
Connection con = DBConnection.getConnection();
//set up query string
this.teacherQuery = "SELECT * FROM users WHERE type=2";
try {
//prepare statement
PreparedStatement teacherState = con.prepareStatement(teacherQuery);
//execute query
ResultSet teachResult = teacherState.executeQuery();
//clear previous items to avoid duplicates.
jComboBox_teachers.removeAllItems();
//create counter variable to get different teachers in RS
int i = 0;
//while loop
while(teachResult.next()){
//get username then add it to position i at combobox
String tempOption = teachResult.getString("username");
System.out.println(tempOption);
jComboBox_teachers.addItem(tempOption); //thanks mcalpine
//increment i
i++;
}
} catch (SQLException ex) {
Logger.getLogger(FeedbackForm.class.getName()).log(Level.SEVERE, null, ex);
}
Found the bug! I needed to make a close-if feature on my Connection class.
Here's the code, should anyone want it:
public class DBConnection{
public static Connection con = null;
public static Connection getConnection(){
//initialise connection
try{
//creates valid url to access DB with
String url = "jdbc:sqlite:" + System.getProperty("user.dir") + "/TeacherReviewIA.DB";
if(con == null){
con = (Connection) DriverManager.getConnection(url);
}else{
con.close();
con = (Connection) DriverManager.getConnection(url);
}
//as a debug measure and to show connection given
System.out.println(con);
}
catch(SQLException ex){
JOptionPane.showMessageDialog(null,ex,"WARNING",JOptionPane.WARNING_MESSAGE);
}
//allows code that called method to use connection given
return con;
}
}
This question already has answers here:
Non-static variable cannot be referenced from a static context
(15 answers)
Closed 1 year ago.
I am new to java and started doing a javaFX project. In this project, I receive a variable from a previous frame, and use it to execute an SQL query in order to render the table based on that particular variable.
Here is my code:
package financials;
import java.net.URL;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ResourceBundle;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javax.swing.JOptionPane;
/**
* FXML Controller class
*
* #author param
*/
public class theControl implements Initializable {
#FXML
private Label test;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
Statement st;
Connection con = null;
}
/**
*
* #param name
*/
public void previous(String name) {
System.out.println(name);
}
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database", "root", "Password");
return con;
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
}
public static ObservableList<RenderNow> getListAccount() {
Connection con = ConnectDB();
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code=? ");
pst.setString(1, name); //This is where I am having trouble
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
}
The problem is that the variable name is not being recognized in the pst.setString line. The error I am getting is that variable 'name' is not found. I tried a different approach where I used name to set the text of Label test, and then later tried to get the variable in the public static Connection ConnectDB() method.
Something like:
public class theControl implements Initializable {
#FXML
private Label test;
/**
* Initializes the controller class.
*/
#Override
public void initialize(URL url, ResourceBundle rb) {
Statement st;
Connection con = null;
}
/**
*
* #param name
*/
public void previous(String name) {
System.out.println(name);
test.setText(name); //Where i set the text of label 'text'
}
public static Connection ConnectDB() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost/database", "root", "Password");
return con;
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
}
public static ObservableList<RenderNow> getListAccount() {
String name2 = test.getText(); //Where I try and get the text from label 'text'
Connection con = ConnectDB();
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code=? ");
pst.setString(1, name2); //This is where I am having trouble
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
}
However, this attempt returns an error non-static variable test cannot be referenced from a static context. My understanding is that since the label test is not static, static Connection is unable to get the text. Is there any work around for this ?
In your first case, the variable was not set. It's only available on the method where you have your print method.
In the second case, you are not using the object. The test variable is in one object, so not accessible by static method which are not depending of object.
I suggest you to ad new parameter to your static method, and use like this:
// create new static method which require the name in parameters
public static ObservableList<RenderNow> getListAccountWithName(String name) {
Connection con = ConnectDB(); // get DB thanks to static method
ObservableList<RenderNow> list = FXCollections.observableArrayList();
try {
PreparedStatement pst = con.prepareStatement("SELECT * FROM lines WHERE Code = '?'");
pst.setString(1, name); // now you can use name value
ResultSet rs = pst.executeQuery();
while (rs.next()) {
list.add(new SBRender(rs.getString("Account1"), rs.getString("Account2"), rs.getString("Account3"), rs.getString("Account4"), rs.getString("Account5")));
}
} catch(Exception ae) {
JOptionPane.showMessageDialog(null, ae);
return null;
}
return list;
}
And now, you can call it from the object like:
ObservableList<RenderNow> accounts = getListAccountWithName(test.getText());
// now what you have what you are looking for
I've read about inheritance or using the import. I just simply am unable to get the right answer. Firstly my code is of the following form:
class queries{
String query1="Select * from "+tableName+";
String query2="Select "+columnName+" from "+tableName+";
}
Now, I have another class where I wish to make make SQL queries using the queries mentioned in the queries class:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
class test{
public static void main(String args[])throws SQLException
{
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("This is Wrong");
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection connect = DriverManager
.getConnection("SQLCONNECTION");
PreparedStatement preparedStatement = connect
.prepareStatement(THIS SHOULD CALL query1 or query2);
ResultSet resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
System.out.println("THIS RUNS");
//display text
}
preparedStatement.close();
connect.close();
}
}
So well, I need to figure out how to call query1 or query2 from the queries class in test. Sorry, but I hope someone can help me how to do this in a clean way. I can also create a Hashtable in queries where I call the respective query based on its name.
Thanks a lot.
class queries
{
public static String getQuery1(String tableName)
{
return "Select * from "+tableName;
}
public static String getQuery2(String tableName, String columnName)
{
return "Select "+columnName+" from "+tableName;
}
}
Then do this:
PreparedStatement preparedStatement =
connect.prepareStatement(queries.getQuery1("INSERT TABLE NAME HERE"));
I have a JDBC:ODBC connection to a MS Access Database which populates a JTable with DButils. My basic SQL queries work fine until I try the COUNT function and then I get errors when trying to populate my JTable. The query works fine to populate a JTextArea so I know the query is ok.
My code is below any help would be greatly appreciated.
import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import java.sql.*;
import net.proteanit.sql.DbUtils;
public class table {
Connection con;
Statement st;
ResultSet rs;
public table(){
connect();
}
public void connect(){
JTable tbl = new JTable();
tbl.setDefaultEditor(Object.class, null);
JFrame resFrame = new JFrame("Results");
resFrame.setLayout(null);
resFrame.setSize(525, 445);
resFrame.setVisible(true);
JScrollPane tsp = new JScrollPane(tbl);
tsp.setLocation(20, 20);
resFrame.add(tsp);
tbl.setAutoResizeMode(JTable.AUTO_RESIZE_OFF);
tsp.setSize(370,375);
String sql = "SELECT Club, COUNT('memberID') AS total FROM Members_Table, Club_Table WHERE Club_Table.clubID=Members_Table.clubID GROUP BY Club";
try{
String driver = "sun.jdbc.odbc.JdbcOdbcDriver";
Class.forName(driver);
String db = "jdbc:odbc:ITUKdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = st.executeQuery(sql);
tbl.setModel(net.proteanit.sql.DbUtils.resultSetToTableModel(rs));
}catch(Exception ex){
}
}
}
The error I get is below
java.sql.SQLException: [Microsoft][ODBC Driver Manager] Invalid cursor state
at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6956)
at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:7113)
at sun.jdbc.odbc.JdbcOdbc.SQLGetDataString(JdbcOdbc.java:3906)
at sun.jdbc.odbc.JdbcOdbcResultSet.getDataString(JdbcOdbcResultSet.java:5697)
at sun.jdbc.odbc.JdbcOdbcResultSet.getString(JdbcOdbcResultSet.java:353)
at sun.jdbc.odbc.JdbcOdbcResultSet.getObject(JdbcOdbcResultSet.java:1677)
at net.proteanit.sql.DbUtils.resultSetToTableModel(DbUtils.java:28)
at trial.table.connect(table.java:53)
at trial.table.<init>(table.java:22)
at trial.ITUKSQL.main(ITUKSQL.java:212)
Sorted had to remove
ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE
From
st = con.createStatement();
I'm new in java.
how can I get the data from mysql and display it in Jlist (Jlist name: JLISTF)
I'm confused with vector and the model.
Below is the photo of my JFRAME
the yellow part means JLIST and it's name is JLISTF
I want to display the data from mysql
Thank you
code:
public class Inventory extends javax.swing.JFrame {
Connection connect = null;
ResultSet rs = null;
PreparedStatement pst = null;
ResultSet rs2 = null;
public void populateJList(JList ItemList, String query, Connection connection) throws SQLException
{
DefaultListModel model = new DefaultListModel(); //create a new list model
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query); //run your query
while (resultSet.next()) //go through each row that your query returns
{
String ItemList2 = resultSet.getString("ItemCode"); //get the element in column "item_code"
model.addElement(ItemList2); //add each item to the model
}
ItemList.setModel(model);
resultSet.close();
statement.close();
}
public Inventory() {..}
private void searchButtonActionPerformed(java.awt.event.ActionEvent evt) { ......}
private void saveButton3ActionPerformed(java.awt.event.ActionEvent evt) {
String inventcodef = inventCodeField.getText();
try{.........}
catch()
{...........}
}
Assuming you have a connection to your database and you know what information you want to query, you can use the following method to populate your JList.
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.swing.DefaultListModel;
import javax.swing.JList;
...
public void populateJList(JList list, String query, Connection connection) throws SQLException
{
DefaultListModel model = new DefaultListModel(); //create a new list model
Statement statement = connection.createStatement();
ResultSet resultSet = statement.executeQuery(query); //run your query
while (resultSet.next()) //go through each row that your query returns
{
String itemCode = resultSet.getString("item_code"); //get the element in column "item_code"
model.addElement(itemCode); //add each item to the model
}
list.setModel(model);
resultSet.close();
statement.close();
}
You would pass your JLISTF variable into this function as the first parameter.
The following line assumes that your column name is "item_code", you will want to replace this with your columns actual name.
String itemCode = resultSet.getString("item_code");
This function creates a new Model (see How to Use Models), then executes your query. It gets each value that your query returns and adds it to the new model. list.setModel(model) then tells the list to start using your new model.