SELECT COUNT from MS Access to a JTable with DButils - java

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();

Related

SQL connection busy although it's already closed

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;
}
}

Can`t make insert in Oracle database from JSF Java web app

I have a JSF webapp and I encountered one problem. I want to take data that is from one table and is inserted in a datatable and insert it into a log table in the database.
I did the connection with the database but it doesn't show any errors and it doesn't insert anything.
I went in with the debugger from netbeans and the variables that I want to insert have values. I do not know where the problem is.
Here is the code:
package com.spv.raport;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.inject.Named;
import javax.enterprise.context.RequestScoped;
import javax.sql.DataSource;
import oracle.jdbc.pool.OracleDataSource;
#Named(value = "dateBean")
#RequestScoped
public class DateBean {
private List<Date> dateList = new ArrayList<>();
public DateBean() throws ClassNotFoundException, SQLException {
String host = "jdbc:oracle:thin:#xxx:1521:xxx";
String user = "xxx";
String pass = "xxx";
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection(host, user, pass);
Statement stmt = con.createStatement();
String sql = "select utilizator, tip_cerere, parametri, stare from
cereri where tip_cerere='D394' and utilizator='44192556' ";
ResultSet rs = stmt.executeQuery(sql);
String u = null;
String t = null;
String p = null;
String s = null;
String d = null;
while(rs.next()) {
u = rs.getString("utilizator");
t = rs.getString("tip_cerere");
p = rs.getString("parametri");
s = rs.getString("stare");
// d = rs.getString("creation_date");
dateList.add(new Date(u,t,p,s));
}
String host2 = "jdbc:oracle:thin:#xxx:xxx";
String user2 = "xxx";
String pass2 = "xxx";
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con2 = DriverManager.getConnection(host2, user2, pass2);
Statement stmt2 = con2.createStatement();
String sql2 = "insert into SPV_RAPORT_LOG values ('serban', '123',
'parametru_test')";
stmt2.executeUpdate(sql);
} catch(SQLException se) {System.out.println(se);}
catch(Exception e) {System.out.println(e);}
}
public List<Date> getDateList() {
return dateList;
}
}
The database host and name and user and passwords are put intentionally with xxx to hide them.
I am a beginner and I do not have any idea why it doesn`t insert the test statement into the database table

Sybase jdbc4 not returning any results from sql query

I'm trying to run a query against a Sybase database. It seems like the connection is made successfully but when it hits rs.next() it fails to go to the first row in the results. It jumps down to the rs.Close().
I know for a fact that my query below works. I'm running it in a sql tool and it returns one record.
Please can someone tell me what I'm doing wrong?
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.*;
import com.sybase.jdbc4.jdbc.SybDataSource;
import com.sybase.jdbc4.jdbc.SybDriver;
public class test {
public static void main(String[] args) throws SQLException {
SybDriver sybDriver = null;
Connection conn = null;
Statement stmt = null;
String host = "123.12.34.56";
String url = "jdbc:sybase:Tds:"+host+":1300";
String username = "testuser";
String password ="password";
try{
sybDriver=(SybDriver)Class.forName("com.sybase.jdbc4.jdbc.SybDriver").newInstance();
conn = DriverManager.getConnection(url, username, password);
stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("select top 1 brand, model,color,serialnum from myTable order by newid()");
while(rs.next())
{
String one = rs.getString(1);
String two = rs.getString(2);
String three = rs.getString(3);
String four = rs.getString(4);
}
rs.close();
stmt.close();
conn.close();
} catch(SQLException | InstantiationException | IllegalAccessException | ClassNotFoundException ex) {
}
}

How to display multiple records of mysql in java

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.

how to get data from mysql to jList?

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.

Categories