I'm trying to populate my combo box with incremental ID's from my ms access database, when I run my program the program runs fine although there is no data inside the combo box and no error given from the console. Can anyone have a look through my code to see how I'm going wrong?
private JComboBox comboBox;
Connection con;
PreparedStatement pst;
ResultSet vResults;
Statement vStatement;
void updatecombo() throws SQLException {
try {
con = connectionz.getConnection();
vStatement = con.createStatement();
String vQuery = "SELECT Book_ID FROM books";
vResults = vStatement.executeQuery(vQuery);
while(vResults.next()) {
comboBox.addItem(vResults.getString("Book_ID"));
}
} catch (Exception e) {
}
}
Database
empty list
If "Book_ID" is really a string and not a numeric, problem might be with connection. If no errors exist, it might be connected to duplicate server with no data in it.
vResults.get**String**("Book_ID")
The issue was, I wasn't initialising the combo box correctly. Thanks for the comments I was completely overlooking that I wasn't printing the exception and getting to caught up in the SQL.
Related
I am trying to access a database from a different server , but no success so far. The event is, when I choose the object "ALL" in my combobox, the table will load all data from different servers.
The current code, which I only connected to the localhost, works fine. However, when I try to connect another server to load both of their data, I get a syntax error when trying to put 192.168.1.51.sales.items in the String sqlall. Also, I tried modifying the prepareStatement by writing cn.prepareStatement(sqlall) + cn1.prepareSatement("union Select * from 192.168.1.52.sales.items); I have no more idea on how to connect on both servers.
I would like to apologize beforehand if you find my coding a bit messy. Thank you. My code is as follows:
private void combobox_branchItemStateChanged(java.awt.event.ItemEvent evt) {
Object branch = combobox_branch.getSelectedItem();
try
{
// All is selected
if("All".equals(branch))
{
Connection cn = db.itemconnector.getConnection();
String sqlall = " Select * from sales2.items union Select * from sales1.items union Select * from sales.items " ; //I tried accessing multiple databases in my own localhost and worked.
PreparedStatement ps = cn.prepareStatement(sqlall);
ResultSet rs = ps.executeQuery();
DefaultTableModel tm = (DefaultTableModel)itemTable.getModel();
tm.setRowCount(0);
while(rs.next())
{
Object o[] = {rs.getInt("id"), rs.getString("location"), rs.getString("product_name"),rs.getString("product_category"),rs.getString("product_description"),rs.getInt("product_stock"), rs.getFloat("product_price"), rs.getString("product_status")};
tm.addRow(o);
}
}
catch (Exception e)
{
JOptionPane.showMessageDialog(null, e, "Connection Error", JOptionPane.ERROR_MESSAGE);
}
}
And I have a class in a different package and this is its code:
package db;
import java.sql.*;
public class itemconnector {
public static Connection getConnection() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales","root","");
return cn;
}
It is not possible to query different databases on different servers in a single SQL query.
It is also not possible to get around this by "concatenating" prepared statements. (For a start, that is nonsensical Java!)
You need to open a separate Connection to each separate database server and query the relevant tables on that server. Then combine the information from the separate ResultSet objects in Java code.
The "combining" will be something like iterating the results in each result set and adding them to a Java data structure ...
I am trying and failing to send data from my java gui to my MS SQL database, I have dabbled with Java in the past but by no means am I an expert, I have been sourcing help from online and I have managed to connect my database to my application but i seem to be struggling with transferring data from the text fields to the database. (I am also new to stack so please put me straight in my place if I am out of line)
I have a class for my UI and a class for the database connection, the code is from a online resource and it seems straight forward and logical to follow (in my eyes) but I cannot seem to crack what should be a simple problem. The process is get the text from the text field and insert using a statement in to the SQL database, I can send data from within my code easily but I would ideally like it from the text fields.
The code cannot seem to see the "Connection" - error = java.lang.RuntimeException: Uncompilable source code - cannot find symbol
symbol: class Connection
I apologise in advance if this is a very simple mistake but it is driving me insane as it should be a fairly straight forward process. In plain terms it should be able to fill out the four text fields which fill the four columns in my DB when the submit button is pressed. Any help would be greatly appreciated.
this is the code for the action on my button:
private void SubmitBTNActionPerformed(java.awt.event.ActionEvent evt) {
String name = Name.getText();
String number = Number.getText();
String title = Title.getText();
String year = Year.getText();
String query = "insert into students values ('"+Name+"','"+Number+"','"+Title+"','"Year+"')";
System.out.println(query);
try {
Connection c = DatabaseConnection.getConnection();
Statement stmt = c.createStatement();
stmt.executeUpdate(query);
} catch (Exception e) {
e.printStackTrace();
}
}
this is the code in my database class
public class DatabaseConnection {
static private Connection connection;
public static Connection getConnection() throws Exception{
if(connection == null){
//JDBC
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
connection = DriverManager.getConnection("jdbc:sqlserver://localhost:1433;databaseName=*******;user=****;password=******;");
}
return connection;
}
}
Thanks
I have a table with 7 columns and I'm trying to connect my database with it so as to receive data from the database and show it in the table. The code works fine when you press the button the first time but when you press it a second time, the table becomes blank and i get this error:
java.lang.ArrayIndexOutOfBoundsException: 0 >= 0
I have given my code below for the ActionPerformed method of the button.
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_name","root","admin123");
String query="SELECT * FROM tablename;";
Statement st = con.createStatement();
ResultSet rs= st.executeQuery(query);
DefaultTableModel tmodel = (DefaultTableModel) jTable1.getModel();
int rows=tmodel.getRowCount();
while(rows>0)
{
tmodel.removeRow(0);
}
jTable1.setModel(tmodel);
while(rs.next())
{
tmodel.addRow(new Object[] {rs.getInt("column1"),rs.getString("Column2"),rs.getString("Column3"),rs.getInt("Column4"),rs.getString("Column5"),rs.getString("Column6"),rs.getString("Column7")});
jTable1.setModel(tmodel);
}
}
catch(Exception ex)
{
System.out.println("Eception: "+ex);
}
Any help would be greatly appreciated.
your problem is with this part although it is a relatively simple fix:
int rows=tmodel.getRowCount();
while(rows>0)
{
tmodel.removeRow(0);
}
jTable1.setModel(tmodel);
what you want to do is:
while(tmodel.getRowCount()>0)
{
tmodel.removeRow(0);
}
jTable1.setModel(tmodel);
because you are setting a variable to a constant value returned by the method which means it wont be updated as you continue to delete rows
Since you never update rows inside the loop, the while will keep going forever or until an Exception is reached...
while(rows>0)
{
tmodel.removeRow(0);
}
And of course, setRowsCount() will be way simpler and less error prone.
BTW: Helping you would be easier if you pointed which line was the one throwing the exception.
I have a button called ‘View Records’. The idea is that when I click it, it displays all the records from the database in a table.
I am able to retrieve the records from the database and display them using System.out.println or JOptionPane.showMessageDialog functions however when trying to display it using a Jtable, I cannot seem to figure out what I am doing wrong.
I am new to Java and trying to teach some to myself, but I’ve been stuck at this for some time. Help would be much appreciated.
import net.proteanit.sql.DbUtils;
JTable employee_table;
class home extends JFrame implements ActionListener
public void actionPerformed(ActionEvent click)
if(click.getSource()==view_records)
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection connect=DriverManager.getConnection("jdbc:mysql://privatedb/employee","sava","123456");
Statement stmt=connnect.createStatement();
ResultSet rsemp = stmt.executeQuery("SELECT * FROM employee");
employee_table.setModel(DbUtils.resultSetToTableModel(rsemp));
}
catch(Exception e){
System.out.println(e.getMessage());
} finally {
This is not a Swing problem but a Java problem -- you can't work with variables if they are null. You first need to assign objects to them.
So if you get a NullPointerException, look at that line and then check to see which variable you're trying to use on that line and fix it.
Here you need to create a new JTable and assign it to the JTable variable.
Keep studying and keep reading. Consider studying basic Java first, and then moving to Swing later.
In the future, if you have similar problems, post your error messages with your question, show which line in your code is causing the error (the error/exception message will tell you).
first of all u have to download a library file rs2xml.jar(easily available).
put/include it into ur application library
import the library file by
import net.proteanit.sql.DbUtils;
connect to the database by
private void connecting() {
try
{
JavaDBConnectivity dbobj=new JavaDBConnectivity();
conn=dbobj.Connect();
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e );
}
}
// i hope u have a created a class for connecting to database(JavaDBConnectivity here)
u can create a button then add an event on mouseclick(use netbeans to do it easily)
private void submit_queryMouseClicked(java.awt.event.MouseEvent evt) {
try{
connecting();
// String query ="select * from "database name""; //use this or if u have text area for entering use the below statement
String query=QueryArea.getText();
pst = conn.prepareStatement(query);
rs = pst.executeQuery();
s.append (QueryArea.getText()).append("\n");
jTable.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(Exception e){
JOptionPane.showMessageDialog(null,e );
}
}
after getting the ResultSet rsemp, use the following code
DefaultTableModel dtm=(DefaultTableModel) employee_table.getModel();
while(rsemp.next()){
Vector v1=new Vector();
//in the below manner do this for all the columns in ur table
v1.add(rsemp.getString("column1Name"));
v1.add(rsemp.getString("column2Name"));
//after adding like that
dtm.addRow(v1);
}
i am using java sqlite (org.sqlite.JDBC) with this i am adding a new row of data to the table, one field is supposed to take up a big amount of base64 encoded data (like pdf) the type of this field is sql-TEXT. now, if i delete the row with "DELETE FROM table WHERE id='id'" the row gets deleted as expected, my sqlite browser confirms this. but the table was befor the deletion like 4KB big, after adding the row it was 12MB and after deleting it remains 12MB big. is there a kind of cleanup i have to do?
in sqlite admin(http://sqliteadmin.orbmu2k.de/) there is a "Cleanup" button after pressing that everything is fine, which means the database shrinks to its size befor adding stuff (4KB). after asking google i realy cannot find such a sql command. it seems that only the index informations get deleted from my databasefile, not the content itself. this behavior is known from windows delete functions.
beside that, here is the java snippet i use:
public void deleteRowById(String table, int id){
try {
Connection connection = null;
Class.forName("org.sqlite.JDBC");
connection = DriverManager.getConnection("jdbc:sqlite:C:\\meinedb");
//statement = connection.createStatement();
String sql = "DELETE FROM "+table+" WHERE id='"+id+"'";
PreparedStatement pstmt = connection.prepareStatement(sql);
pstmt.executeUpdate();
pstmt.close();
connection.close();
} catch (SQLException ex) {
Logger.getLogger(FileSpinner.class.getName()).log(Level.SEVERE, null, ex);
} catch (ClassNotFoundException ex){
}
}
You can shrink a SQLite database with the VACUUM statement. Read the manual I link to for details.