I am trying to add ComboxItem from database. I have write the code given below. When I run the program it give a error message.
Message is
java.sql.SQLException:Driver does not support this function
someone please help me.
here is my code
public class DepositFirstForm extends javax.swing.JFrame {
Connection conn=null;
ResultSet rst=null;
PreparedStatement pst=null;
private void ItemComb(){
private void ItemComb(){
String sql="SELECT * FROM account_type";
try
{
pst=conn.prepareStatement(sql);
rst=pst.executeQuery(sql);
while(rst.next()){
String actype=rst.getString("account_type");
dfcmb1.addItem(actype);
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
}
}
private void formWindowOpened(java.awt.event.WindowEventevt) {
// TODO add your handling code here:
conn=Connect.connectDB();
ItemComb();
}
}
my table name is account_type
serial_no account_type
1 regular
2 premium
3 golden
Try removing the (sql) parameter from you call to pst.executeQuery:
rst = pst.executeQuery();
Since your PreparedStatement is already created using the SQL.
I trust you are declaring conn, pst and rst somewhere.
Related
So I'm currently working on a project that will be using a database but its my first time trying fiddling with it on java.
But I'm already seeing my first problem is how would i make one single file that handles connection while other files handles GET/ADD/UPDATE/DELETE (one for each table) what would properly be the best way on doing this ?
To not having to place connection values in each file and do the connection
I though about extending the connection class with the other classes but idk if its a great idea.
import java.sql.*;
public class DatabaseConnection {
public static void main(String[] args) {
final String url = "jdbc:postgresql://localhost:5432/Database";
final String user = "dbuser";
final String password = "dbpass";
try(Connection conn = DriverManager.getConnection(url, user, password)) {
System.out.println("Connection successful!");
} catch (SQLException e) {
System.out.println("Connection failure.");
e.printStackTrace();
}
}
}
What would be the best approach?
Maybe i'm wrong, but i think you need connection pool.
Try to find instruction here https://www.baeldung.com/java-connection-pooling
You could move the database connection related code to a utility class, and use the PreparedStatement class to precompile the SQL Query
public class doSomething {
Connection conn = null;
PreparedStatement pst = null;
public static void main(String [] args){
conn = DatabaseConnection.connect()
String qry = "Select * from table_name";
pst = (PreparedStatement) conn.prepareStatement(qry);
}
}
I'll try my best to make this as clear as possible since I'm new to Java. If there are parts which are unclear to you, please let me know. I apologize beforehand if the structure of my coding is messy.
I'm making a combobox event wherein if an item is selected (or changed), it will display items of that database and if the Update button is clicked, the program will connect to the database based on the item selected in the combobox.
The problem is that the variable cn after the if-else statement, has an error of "variable may have not been initialized".
Please note that I would like to focus on the condition since it is where I'm having difficulties and that the Update part is not a concern at this time.
private void btn_UpdateActionPerformed(java.awt.event.ActionEvent evt)
{
String value2 = (String) combobox_location.getSelectedItem();
String value4 = (String) combobox_category.getSelectedItem();
try
{
if(value2.equals(value4))
{
Connection cn = db.itemconnector.getConnection();
}
String sql = "UPDATE items set location = '"+value2+"' where id = '"+value4+"' " ; //Please ignore this line for the now
PreparedStatement ps1 = cn.prepareStatement(sql);
ps1.execute();
JOptionPane.showMessageDialog(null, "Update Successful");
PreparedStatement ps2 = cn.prepareStatement(ref);
ResultSet rs = ps2.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)
{
System.out.println("Update Error!");
}
}
I have a package db that has itemconnector class for database connection and here is my code I've written in it. I hope I have provided all necessary details for your assistance. If you need more info, please let me know. Thank you.
package db;
import java.sql.*;
public class itemconnector {
/**
*
* #return
* #throws Exception
*/
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;
}
public static Connection getConnection1() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales1","root","");
return cn;
}
public static Connection getConnection2() throws Exception
{
Class.forName("com.mysql.jdbc.Driver");
Connection cn = (Connection)
DriverManager.getConnection("jdbc:mysql://192.168.1.50:3306/sales2","root","");
return cn;
}
}
first time posting so sorry if my question is slightly strange.
So I have a project in school that requires us to create java classes using netbeans that open up a window with three options, check stock, purchase item and update stock.
We had a class called stockdata that held the details of 5 different items for us to use in our three classes to check, purchase and update items. The latest stage of our coursework requires us to create a derby database and enter the items into a table.
I have done this with no issues but I am having a problem getting the items from the table back into my classes to use. We were given the following code but I can't get it to work, even using the commented hints.
package stock;
// Skeleton version of StockData.java that links to a database.
// NOTE: You should not have to make any changes to the other
// Java GUI classes for this to work, if you complete it correctly.
// Indeed these classes shouldn't even need to be recompiled
import java.sql.*; // DB handling package
import java.io.*;
import org.apache.derby.drda.NetworkServerControl;
public class StockData {
private static Connection connection;
private static Statement stmt;
static {
// standard code to open a connection and statement to an Access database
try {
NetworkServerControl server = new NetworkServerControl();
server.start(null);
// Load JDBC driver
Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
//Establish a connection
String sourceURL = "jdbc:derby://localhost:1527/"
+ new File("UserDB").getAbsolutePath() + ";";
connection = DriverManager.getConnection(sourceURL, "use", "use");
stmt = connection.createStatement();
} // The following exceptions must be caught
catch (ClassNotFoundException cnfe) {
System.out.println(cnfe);
} catch (SQLException sqle) {
System.out.println(sqle);
} catch (Exception e) {
System.out.println(e);
}
}
// You could make methods getName, getPrice and getQuantity simpler by using an auxiliary
// private String method getField(String key, int fieldNo) to return the appropriate field as a String
public static String getName(String key) {
try {
// Need single quote marks ' around the key field in SQL. This is easy to get wrong!
// For instance if key was "11" the SELECT statement would be:
// SELECT * FROM Stock WHERE stockKey = '11'
ResultSet res = stmt.executeQuery("SELECT * FROM Stock WHERE stockKey = '" + key + "'");
if (res.next()) { // there is a result
// the name field is the second one in the ResultSet
// Note that with ResultSet we count the fields starting from 1
return res.getString(2);
} else {
return null;
}
} catch (SQLException e) {
System.out.println(e);
return null;
}
}
public static double getPrice(String key) {
// Similar to getName. If no result, return -1.0
return 0;
}
public static int getQuantity(String key) {
// Similar to getName. If no result, return -1
return 0;
}
// update stock levels
// extra is +ve if adding stock
// extra is -ve if selling stock
public static void update(String key, int extra) {
// SQL UPDATE statement required. For instance if extra is 5 and stockKey is "11" then updateStr is
// UPDATE Stock SET stockQuantity = stockQuantity + 5 WHERE stockKey = '11'
String updateStr = "UPDATE Stock SET stockQuantity = stockQuantity + " + extra + " WHERE stockKey = '" + key + "'";
System.out.println(updateStr);
try {
stmt.executeUpdate(updateStr);
} catch (SQLException e) {
System.out.println(e);
}
}
// close the database
public static void close() {
try {
connection.close();
} catch (SQLException e) {
// this shouldn't happen
System.out.println(e);
}
}
}
Sorry if this seems a stupid question but I am fairly new to Java and was making good progress until this roadblock.
Thanks in advance!
Alex
Searching for "java sql" on Google delivers this link: https://docs.oracle.com/javase/tutorial/jdbc/basics/processingsqlstatements.html
From a connection you can create a statement (you can find this in the link and in your code) , then fetch a result set and loop over that with rs.next(). That should get your started.
Of course you have to make sure that the driver and database are there/running, just saying...
Here netbeans has nothing to do with database. This is a Java-based integrated development environment(IDE) that will help you to reduce syntactic error.
public void dataAccess(){
try {
String connectionUrl = "suitable connection url as per your database";
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
Class.forName("JDBC driver name as per your database");
con = DriverManager.getConnection(connectionUrl, userName, password);
String SQL = "SQL query as per your criteria";
stmt = con.createStatement();
rs = stmt.executeQuery(query);
while (rs.next()) {
// look into ResultSet api and use method as per your requirement
}
rs.close();
}
catch (Exception e) {
//log error message ;
}
}
I have some issues with the conection between java application and mysql.
This is my file(this file work very well):
import java.sql.*;
import javax.swing.JFrame;
public class MysqlConnect{
public static void main(String[] args) throws SQLException {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "jdbctutorial";
String driver = "com.mysql.jdbc.Driver";
String userName = "birthday";
String password = "123456";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
} catch (Exception e) {
e.printStackTrace();
}
}
}
Is possible "to separate" the main and mysql connection ??
My idea is something like that :I have the MysqlConnection file and another GUI file.
In the GUi file I have a button (ADD) and whenever I click this button some datas will be stored to database .My problem is that I don't know how run the query ,because I need the Statement variable ,Connection variable,etc..What I suppose to do ?To do the mysqlConnection and GUI in the same file ?Another idea of mine is to do an object of type MysqlConnection and work with that object.And here is the problem :If I remove the (public void main .....) i have an error at try and catch.
Sorry if my english is bad but I hope i make myself clear .
Thanks in advance .
What I understand from your question is that you want to make an application that shows data from a database in a GUI. Maybe you should look into an architecture like MVC (Model-View-Controller) where you have the model as an representation of the data in the database and having the view as a graphical representation of the model.
Since it didn't came to mind to apply a certain architecture, I would recommend you to look into that first, do a little bit of research and then implement your system. When looking into the MVC-architecture, I recommend you to start here. This is really the most easy example you could think of.
About your database connection: your setup looks good, though first of all, put it in a separate class and add query functionality to it. While implementing that part, this would come in handy. After that, you can let the Controller call the database to manipulate the Model on a button press, which will update the View (GUI) in your MVC-architecture.
So, do NOT put your database connection and your Main or GUI in the same class! This is a bad code style, violates the Single Responsibility Principle and will give you more trouble in future developing! Instead, use a proper architecture
If you want further help, always feel free to ask! I have recently studied this kind of stuff and made an application like this.
Hi RvanHeest thank you very much for your time.I try to do like that :
MysqlConnect.java
public class MysqlConnect{
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public String query="Select * From Person";
public Statement stmt;
public ResultSet rs;
public void crearedatabase(){
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
Statement stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
and in mine Gui class like that :
GUi file:
.................
................
MysqlConnect mysqlitem = new MysqlConnect();
mysqlitem.crearedatabase();
String query = "INSERT INTO persons("
+ "id"
+ "name"
+ "lastname"
+ "date) "
+ "VALUES(null,Maxim,Alexandru-Vasile,1990-12-28)";
try{
mysqlitem.rs=mysqlitem.stmt.executeQuery(query);
}
catch(Exception e1){
System.out.println("Eroare");
}
On the " mysqlitem.rs=mysqlitem.stmt.executeQuery(query);" I have an Exeption error and I don't know how to resolve..
Thank you very much again !!!
I ran in to the same issue.
I found the root cause to be that you are declaring the stmt variable twice.
Your code should look this like:
public class MysqlConnect{
public Connection conn = null;
public String url = "jdbc:mysql://localhost:3306/";
public String dbName = "jdbctutorial";
public String driver = "com.mysql.jdbc.Driver";
public String userName = "birthday";
public String password = "123456";
public String query="Select * From Person";
public Statement stmt;
public ResultSet rs;
public void crearedatabase(){
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
System.out.println("Connected to the database");
stmt = conn.createStatement();
} catch (Exception e) {
System.out.println("Error!!!");
}
}
}
Note the change to the line 18 "stmt = conn.createStatement();"
I wrote this code for create a separate dbconnection class on a separate java file and its working fine for me.
public class dbConnection{
public Connection getConnection()
{
String url = "jdbc:mysql://localhost:88/shop";
String username = "root";
String password = "";
Connection con = null;
try
{
Class.forName("com.mysql.jdbc.Driver");
}
catch (ClassNotFoundException e1)
{
// TODO Auto-generated catch block
e1.printStackTrace();
}
try
{
con = DriverManager.getConnection(url, username, password);
}
catch (Exception e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
}
// USING THE ABOVE CONNECTION ON DIFF CLASS
-----------
Connection con=new dbConnection().getConnection();
------------
Credits to StackOverFlow...
public class LoadDriver {
public static void sqlDriver(String[] args) throws InstantiationException,
IllegalAccessException, ClassNotFoundException {
// TODO Auto-generated method stub
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
and in your main class
try {
LoadDriver.sqlDriver(null);
I am designing a web-service using java and eclipse which returns the user details who are marked as customer in the database
I was successfully able to return details for a single user (as there was only one entry in the dB) with the following code:
public class GetData {
public LoginDetails getDetails(){
Connection conn;
Statement stmt;
ResultSet rs;
try {
LoginDetails lds=new LoginDetails();
Class.forName(driver);
conn=DriverManager.getConnection(url,username,password);
stmt=conn.createStatement();
String sql="select * from login where usertype='customer'";
rs=stmt.executeQuery(sql);
while(rs.next()){
lds.setUsername(rs.getString(1));
lds.setPassword(rs.getString(2));
lds.setUsertype(rs.getString(3));
lds.setActive(rs.getString(4));
}
return lds;
}
catch(ClassNotFoundException c){
c.printStackTrace();
}
catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}
What should I do if there are multiple values in dB matching the criteria and I want to display them all. Please advice.
Change your method signature to public LoginDetails[] getDetails()
And extend your while loop as follows:
Collection<LoginDetails> details = new ArrayList<LoginDetails>();
while(rs.next()){
LoginDetails lds=new LoginDetails();
lds.setUsername(rs.getString(1));
lds.setPassword(rs.getString(2));
lds.setUsertype(rs.getString(3));
lds.setActive(rs.getString(4));
details.add(lds);
}
return details.toArray(new LoginDetails[0]);
Return an collection type suggestively java.util.List , preferably ArrayList from the method.