Java - Populate a JCombobox with SQLite database - java

I want to populate a JComboBox with a database column (SQLite).
My database connection is setup through a class called DatabaseConnection setup in anther package.
Here is how it looks like
import java.sql.*;
import javax.swing.JOptionPane;
public class DatabaseConnection {
Connection conn = null;
public static Connection ConnectDB() {
try {
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:database.db");
JOptionPane.showMessageDialog(null, "Connection Established");
conn.setAutoCommit(false);
return conn;
} catch (Exception e) {
JOptionPane.showMessageDialog(null, e);
return null;
}
}
}
In my JFrame class I am creating following method, which according to a youtube tutorial should work
public void PopulateJCB()
{
String queryString = "SELECT DISTINCT [Account Name] FROM main ORDER BY [Account Name]";
try
{
Connection statJCBaccountname = DatabaseConnection.ConnectDB();
Statement stmt = statJCBaccountname.createStatement();
ResultSet rsJCBaccountname = stmt.executeQuery(queryString);
while (rsJCBaccountname.next())
{
comboAccountName.addItem(rsJCBaccountname.getString(1));
}
catch (SQLException e)
{
e.printStackTrace();
}
}
But it displays following errors at "comboAccountName.addItem(rsJCBaccountname.getString(1));"
Multiple markers at this line
- Type safety: The method addItem(Object) belongs to the raw type JComboBox. References to generic type JComboBox<E> should be
parameterized
- comboAccountName cannot be resolved
Please help!

I'm not really sure what you're expecting...
statJCBaccountname isn't even in the code example you've provided, but the compiler is saying that the variable is undefined
There is no such method as createStatement in the DatabaseConnection class
You need to resolve these issues before the program will compile. I'd suggest staying away from YouTube tutorials unless you know the author.
Take a look at JDBC Database Access for more details...

Related

How to fetch records from Oracle databse using Java

I'm learning database with Java using JDBC. I've created a svery basic program after reading some articles on JDBC on the internet. My code is not giving any error but I'm not getting the output also. Here's is my code:
This is my connectivity code: DataService
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class DataService {
static Connection con;
public static void main(String args[]){
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","system","scott");
}
catch(Exception e){
System.out.println(e);
}
}
public ResultSet getRecords() {
System.out.println("inside getRecords()");
ResultSet rs=null;
try {
System.out.println("Inside Rs loop");
Statement stmt=con.createStatement();
rs=stmt.executeQuery("select * from emp");
System.out.println("RS before entering while: "+rs);
while(rs.next())
System.out.println("Inside while loop");
System.out.println("Data: " +rs.getInt(0)+" "+rs.getString(1));
} catch (SQLException ex) {
Logger.getLogger(DataService.class.getName()).log(Level.SEVERE, null, ex);
}
System.out.println("Before sending: "+rs);
return rs;
}
}
And here's is my application MainFrame.java
public class MainFrame extends Application {
...
#Override
public void start(Stage primarystage) {
...
try {
System.out.println("Inside try");
DataService dataservice = new DataService();
System.out.println("Result set: "+dataservice.getRecords());
} catch (Exception e) {
//TODO: handle exception
}
}
}
I'm getting this output:
Inside try
inside getRecords()
Inside Rs loop
I cant see any output related to records. Also I've checked select * from emp. There are rows in that table already.
I'm missing out something very important here. Please correct me.
When you create DataService instance DataService dataservice = new DataService(); method main() is not called, therefore variable conn is not initialized and remains null. After that when calling Statement stmt=con.createStatement(); a NullPointerException (NPE) is thrown. This NPE is not catched neither in this catch block catch (SQLException ex) because it catches only SQLExceptions nor in this one catch (Exception e), because there is no handling logic provided.
First step in making code work is adding some exception handling logic in method start() of MainFrame class (never leave empty catch blocks, it's considered as an antipattern).
Then move logic for connection initialization either to getRecords() method making it local variable or to DataService constructor, so variable conn will be initialized, when accessing it.
Next big issue is closing Connection, Statement and ResultSet variables after finishing work with them. Since java 7 you can use try-with-resources syntax to handle such resources.
Also I would recommend to handle ResultSet inside of getRecords() method without exposing it outside DataService class.This class acts as Data Access Object (DAO) and it would be better to keep implementation details inside. Instead you could create some simple Employee class, which instances could be initialized inside while(rs.next()) loop, filled with values from result set and added to some collection. This collection could be returned from getRecords() method.
you should obtain connection instance in same thread as you use it
move connection creation to getRecords method

H2 Database, problems getting data from tables

I'm creating a JavaFX application, I've connected to the database fine. However when i look to get data from the tables i get the error
org.h2.jdbc.JdbcSQLException: Table "LECTURE" not found; SQL
statement: SELECT NAME FROM Lecture [42102-192]
and I'm 100% sure i'm connected to the database and the table is definitely there, any suggestions on why this is?
hear is my connection code and the code i am running just so you can see
public class ConnectionFactory {
//static reference to itself
private static ConnectionFactory instance = new ConnectionFactory();
public static final String URL = "jdbc:h2:file:~/db\\.";
public static final String USER = "notepad";
public static final String PASSWORD = "password";
public static final String DRIVER_CLASS = "org.h2.Driver";
//private constructor
private ConnectionFactory() {
try {
Class.forName(DRIVER_CLASS);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
private Connection createConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (SQLException e) {
System.out.println("ERROR: Unable to Connect to Database.");
}
return connection;
}
public static Connection getConnection() {
return instance.createConnection();
}
}
And the query being run
private void onLoadYearSelect() {
try {
Connection con = ConnectionFactory.getConnection();
Statement stat = con.createStatement();
String query = "SELECT NAME FROM Lecture";
ResultSet years = stat.executeQuery(query);
while(years.next()){
yearSelect.setValue(years.getString("NAME"));
System.out.println(years.getString("NAME"));
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public void initialize(){
onLoadYearSelect();
}
If it says the table doesn't exist, then it really doesn't exist.
Most likely, you are not actually connecting to the correct database. In fact, by default, if the connection string points to a non-existent database, it just creates an empty database on the fly, which would explain your error.
It's probably too late now (because there is probably a 2nd database created already somewhere), but to avoid this confusion, it's not a bad idea to include IFEXISTS=TRUE in the connection string so that it fails if the database doesn't exist, rather than creating an empty one that will mask the true problem.
public static final String URL = "jdbc:h2:file:~/db\\.;IFEXISTS=TRUE";
However, one thing you can still try to debug the problem, is to add IFEXISTS=TRUE to the connection string. Then move or rename the database you think it should be connecting to so as to make the connection string invalid. Basically, force it to fail. If the code still connects to the database successfully, then you'll know the connection string is not pointing to the location you think it is.

Connecting with Database in Java in different Frames

I have some doubt when accessing to my SQL DB. The thing is I have a connect Button with this code:
public void actionPerformed(ActionEvent arg0) {
Object opc = arg0.getSource();
if (opc.equals(v.conectar))
{
Connection conexion = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conexion = DriverManager.getConnection("jdbc:mysql://localhost/colegio", "root", "12345");
Statement stm = conexion.createStatement();
JOptionPane.showMessageDialog(null, "CONEXION ESTABLECIDA CON EXITO");
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
In that button, as you see, I connect perfectly with my DB. The problem appears when I need to acced to that Statement object from other JInternalFrame:
public class boton_alta_cliente implements ActionListener {
ventanaAlta v;
boton_alta_cliente(ventanaAlta v) {
this.v=v;
}
public void actionPerformed(ActionEvent arg0, Statement STM) {
Object opc = arg0.getSource();
if (opc.equals(v.alta))
{
ResultSet RS = STM.executeQuery("query");
}
}
}
How can I use that connection I made in my first button, in the JInternalFrame that I use for sign up my clients?
You could create a separate class in your project that handles JDBC connections. So for example, you could have a class called "JDBC" which creates a connection in a "connect()" method. You could then call that connection from your other classes like so:
Connection connect = JDBC.connect();
Like any reference to an object that you want to share between objects, it has to be defined not as a local variable but as a (preferably private) field. You create a getter method for it, and the other frame can use the getter method to access the connection. The same goes for the prepared statement.

How can I connect to a MySQL web server with Java?

Alright, so here's a little bit of background:
I am currently trying to develop a referral application. There is a link on our website where a user can refer their friends to our game server (Minecraft). It will input the referrer's information into a database (hosted on my website) and send a link to the "friend". The friend clicks on the link and enters their information (which also gets stored in the database). All of this is working great! (Yay!) So, now for the Java Plugin!
What is supposed to happen...
I have an Event Listener that will fire whenever a user logs into the game. Essentially, it would check the data base for the user's info, and if the user meets the criteria, then it will award them with their extra referral goodies.
What I am trying to do right now...
Right now, I am essentially trying to just get it to connect and display the id of the row, and the ref_id (Referral ID) when the plugin is enabled. But, I'm getting the following error:
com.mysql.jdbc.exceptions.jdbc4.CommunicationsException: Communications link failure
The last packet sent successfully to the server was 0 milliseconds ago. The driver has not received any packets from the server.
So, without further ado, here is my singular Java document. Of course, that is not the real username and login information to my database. ;) But I'm hoping someone here can tell me what's wrong, because I'm so lost, right now.
package com.arithia.plugins;
import java.sql.*;
import org.bukkit.Bukkit;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerLoginEvent;
import org.bukkit.plugin.java.JavaPlugin;
public class ArithiaReferrals extends JavaPlugin implements Listener {
// JDBC driver name and database URL
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String DB_URL = "jdbc:mysql://66.147.244.122:3306/graphja6_referrals";
// Database credentials
static final String USER = "fake_username";
static final String PASS = "fake_password";
#Override
public void onEnable() {
Connection conn = null;
Statement stmt = null;
try {
// STEP 2: Register JDBC driver
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// STEP 3: Open a connection
getLogger().info("Connecting to database...");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// STEP 4: Execute a query
getLogger().info("Creating statement...");
stmt = conn.createStatement();
String sql;
sql = "SELECT id, ref_id FROM referred_users";
ResultSet rs = stmt.executeQuery(sql);
// STEP 5: Extract data from result set
while(rs.next()) {
// Retrieve by column name
int id = rs.getInt("id");
int ref_id = rs.getInt("ref_id");
// Display values
getLogger().info("ID: " + id);
getLogger().info("Referral ID: " + ref_id);
}
// STEP 6: Clean-up environment
rs.close();
stmt.close();
conn.close();
}catch(SQLException se) {
// Handle errors for JDBC
se.printStackTrace();
}finally{
// finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
} // nothing we can do
try {
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
} // End Finally try
} // end try
getLogger().info("Goodbye!");
getLogger().info("The [Arithia Referrals] plugin was enabled!");
}
#Override
public void onDisable() {
getLogger().info("The [Arithia Referrals] plugin was disabled!");
}
#EventHandler
public void onPlayerLogin(PlayerLoginEvent e) {
// "Check database for player..."
}
}
Other Information...
Database Name: graphja6_referrals
Database Table: referred_users
Note: I am not entirely sure that the DB_URL is correct... 66.147.244.122 is the correct IP, but I'm not entirely sure about the port or anything else, so if someone could verify that's correct, I'd be appreciative.
Thank you very much for your help.
Okay, so I'm just an idiot.
For anyone else getting this error, you need to whitelist the IP of the remote connection for this to work. It is a firewall thing, and depending on who you host with, there's probably a "Remote MySQL" option in the cPanel. Add the IP to the remote client that is trying to access the database, so it will be whitelisted.
Thank you to everyone who tried to help. <3

Executing JDBC MySQL query with this custom method

I've been doing my homework and I decided to re-write my vote4cash class which manages the mysql for my vote4cash reward system into a new class called MysqlManager. The MysqlManager class I've made needs to allow the Commands class to connect to mysql - done and it needs to allow the Commands class to execute a query - I need help with this part. I've had a lot more progress with the new class that I've made but I'm stuck on one of the last, most important parts of the class, again, allowing the commands class to execute a query.
In my MysqlManager class I have put the code to connects to MySql under
public synchronized static void createConnection() {
Now I just need to put the code that allows the Commands class to execute a query under this as well. I've researched and tried to do this for a while now, but I've had absolutely no luck.
The entire MysqlManager class:
package server.util;
/*
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
*/
import java.sql.*;
import java.net.*;
import server.model.players.Client;//Will be needed eventually so that I can reward players who have voted.
/**
* MySQL and Vote4Cash Manager
* #author Cloudnine
*
*/
public class MysqlManager {
/** MySQL Connection */
public static Connection conn = null;
public static Statement statement = null;
public static ResultSet results = null;
public static Statement stmt = null;
public static ResultSet auth = null;
public static ResultSet given = null;
/** MySQL Database Info */
public static String DB = "vote4gold";
public static String URL = "localhost";
public static String USER = "root";
public static String PASS = "";
public static String driver = "com.mysql.jdbc.Driver"; //Driver for JBDC(Java and MySQL connector)
/** Connects to MySQL Database*/
public synchronized static void createConnection() {
try {
Class.forName(driver);
conn = DriverManager.getConnection(URL + DB, USER, PASS);
conn.setAutoCommit(false);
stmt = conn.createStatement();
Misc.println("Connected to MySQL Database");
}
catch(Exception e) {
//e.printStackTrace();
}
}
public synchronized static void destroyConnection() {
try {
statement.close();
conn.close();
} catch (Exception e) {
//e.printStackTrace();
}
}
public synchronized static ResultSet query(String s) throws SQLException {
try {
if (s.toLowerCase().startsWith("select")) {
ResultSet rs = statement.executeQuery(s);
return rs;
} else {
statement.executeUpdate(s);
}
return null;
} catch (Exception e) {
destroyConnection();
createConnection();
//e.printStackTrace();
}
return null;
}
}
The snippet of my command:
if (playerCommand.equals("claimreward")) {
try {
PreparedStatement ps = DriverManager.getConnection().createStatement("SELECT * FROM votes WHERE ip = hello AND given = '1' LIMIT 1");
//ps.setString(1, c.playerName);
ResultSet results = ps.executeQuery();
if(results.next()) {
c.sendMessage("You have already been given your voting reward.");
} else {
ps.close();
ps = DriverManager.getConnection().createStatement("SELECT * FROM votes WHERE ip = hello AND given = '0' LIMIT 1");
//ps.setString(1, playerCommand.substring(5));
results = ps.executeQuery();
if(results.next()) {
ps.close();
ps = DriverManager.getConnection().createStatement("UPDATE votes SET given = '1' WHERE ip = hello");
//ps.setString(1, playerCommand.substring(5));
ps.executeUpdate();
c.getItems().addItem(995, 5000000);
c.sendMessage("Thank you for voting! You've recieved 5m gold!");
} else {
c.sendMessage("You haven't voted yet. Vote for 5m gold!");
}
}
ps.close();
} catch (Exception e) {
e.printStackTrace();
}
}
return;
How the command works:
When a player types ::commandname(in this case, claimreward), the commands function will be executed. This isn't the entire commands class, just the part that I feel is needed to be posted for my question to be detailed enough for a helpful answer.
Note: I have all my imports.
Note: Mysql connects successfully.
Note: I need to make the above command code snippet able to execute mysql queries.
Note: I prefer the query to be executed straight from the command, instead of from the MysqlManager, but I will do whatever I need to resolve this problem.
I feel that I've described my problem detailed and relevantly enough, but if you need additional information or understanding on anything, tell me and I'll try to be more specific.
Thank you for taking the time to examine my problem. Thanks in advance if you are able to help.
-Alex
Your approach is misguided on many different levels, I can't even start to realize what should be done how here.
1) Don't ever use static class variables unless you know what you do there (and I'm certain, you don't)
2) I assume there is a reason you create your own jdbc connection (e.G. its part of your homework) if not, you shouldn't do that. I see you use DriverManager and PreparedStatement in one part, you should continue to use them.
3) Your approach seems to intend to start with a relative good code base (your command part) and then goes to a very low-level crude approach on database connections (your MysqlManager) unless really necessary and you know what you do, you should stay on the same level of abstraction and aim for the most abstract that fits your needs. (In this case, write MysqlManager the way you wrote Command)
4) In your previous question (that you just assumed everybody here has read, which is not the case) you got the suggestion to redesign your ideas, you should do that. Really, take a class in coding principles learn about anti-patterns and then start from scratch.
So in conclusion: Write at least the MysqlManager again, its fatally broken beyond repair. I'm sorry. Write me an email if you have further questions, I will take my time to see how I can help you. (an#steamnet.de)

Categories

Resources