why can't java see my mysql driver - java

I'm having trouble working out why java can't see my mysql driver:
I've downloaded the driver .jar from the mysql website
I've added the jar to my runtime classpath
I can confirm the jar is on the classpath, by printing out the relevant system property
But I'm still getting ClassNotFound Exceptions. Is there anything else I need to be doing?
class example:
package org.rcz.dbtest;
import java.sql.*;
public class DB {
private Connection connect = null;
private Statement stmt = null;
private PreparedStatement prepared = null;
private ResultSet rset = null;
private String driverClassName = "com.myqsl.jdbc.Driver";
private String jdbcUrl = "jdbc:mysql://localhost/ctic_local?user=root&password=server";
private String queryString;
public DB(String query)
{
System.out.println(System.getProperty("java.class.path"));
queryString = query;
}
public void readFromDatabase()
{
try
{
Class.forName(driverClassName);
connect = DriverManager.getConnection(jdbcUrl);
stmt = connect.createStatement();
rset = stmt.executeQuery(queryString);
writeResultSet(rset);
}
catch (ClassNotFoundException cex)
{
System.out.println("Could not find mysql class");
}
catch(SQLException sqex)
{
}
}
private void writeResultSet(ResultSet resultSet) throws SQLException {
// ResultSet is initially before the first data set
while (resultSet.next()) {
// It is possible to get the columns via name
// also possible to get the columns via the column number
// which starts at 1
// e.g. resultSet.getSTring(2);
String user = resultSet.getString("name");
String comment = resultSet.getString("comment");
System.out.println("User: " + user);
System.out.println("Comment: " + comment);
}
}
}
My main class simply passes the query into the DB class:
package org.rcz.dbtest;
import java.io.IOException;
public class Main {
public static void main(String[] args) throws IOException
{
String qstring = "SELECT * FROM comments";
new DB(qstring).readFromDatabase();
System.in.read();
}
}

You've a typo in the driver class name.
private String driverClassName = "com.myqsl.jdbc.Driver";
it should be
private String driverClassName = "com.mysql.jdbc.Driver";
// -------------------------------------^
Unrelated to the concrete problem, holding DB resources like Connection, Statement and ResultSet as an instance variable of the class is a bad idea. You need to create, use and close them in the shortest possible scope in a try-finally block to prevent resource leaking. See also among others this question/answer: When my app loses connection, how should I recover it?

Related

How to instance 1 connection class for multiple requests?

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

Getting error SQLServerException: The result set is closed

I have tried many ways but always i'm getting this error.
Actually i'm trying to access result set values from other class and for Database Query i have created a separate class.
Please do not mark this as previously asked because i got the solution only of single class.
This is my DBVerification class
public class DBVerification {
private static String DB_URL = PropertyManager.getInstance().getDB_URL();
private static String DB_USER= PropertyManager.getInstance().getDB_USER();
private static String DB_PASSWORD= PropertyManager.getInstance().getDB_PASSWORD();
private static String DBClass= PropertyManager.getInstance().getDBClass();
private static Connection connection;
public static ArrayList<ResultSet> executeStoredProcedure(String query) throws ClassNotFoundException, SQLException
{
ArrayList<ResultSet> resultset = new ArrayList<ResultSet>();
Class.forName(DBClass);
connection= DriverManager.getConnection(DB_URL, DB_USER, DB_PASSWORD);
CallableStatement cstmt = connection.prepareCall( "{ call " + query+" }" );
//System.out.println("{ call " + query+" }");
try {
boolean results = cstmt.execute();
int rsCount = 0;
do {
if(results) {
ResultSet rs = cstmt.getResultSet();
resultset.add(rs);
rsCount++;
System.out.println("RESULT SET #" + rsCount);
// rs.close();
}
System.out.println();
results = cstmt.getMoreResults();
} while(results);
//cstmt.getMoreResults(Statement.KEEP_CURRENT_RESULT);
//cstmt.close();
}
catch (Exception e) {
e.printStackTrace();
}
return resultset;
}
public static void closeDB() throws SQLException
{
connection.close();
}
}
This is my second class Reimbursement class
public class Reimbursement
{
ArrayList<ResultSet> result = DBVerification.executeStoredProcedure("getreimbursements");
for (ResultSet curInstance: result) {
if(result.indexOf(curInstance) == 0)
{
while(curInstance.next())
{
String branchName=curInstance.getString("BranchName");
String department=curInstance.getString("DepartmentName");
String employee=curInstance.getString("EmployeeName");
String title=curInstance.getString("Title");
String claimdate=ValueConverter.DateFormat(curInstance.getString("Date"));
}
curInstance.close();
}
if(result.indexOf(curInstance) == 1)
{
while(curInstance.next())
{
String category=curInstance.getString("Category");
String expensedate=ValueConverter.DateFormat(curInstance.getString("ExpenseDate"));
String description=curInstance.getString("Description");
String approvedby=curInstance.getString("ApprovedBy");
}
curInstance.close();
}
}
DBVerification.closeDB();
}
Please do not look for main method because this is for testing class so i'm already using this class in my xml file.
Please give me suggestion that what i'm doing wrong it give me error message that 'The result set is closed'.
Image of exception actually it is my test class so it will display error only in this form i have edited the line which was indicated
exception message
I think your problem might be as follows
you loop around the response to the call to your stored procedure, adding each result set from the call in to an arraylist
you return the arraylist back to your calling method and iterate over it
you try to process each resultset in turn.
Unfortunately, I think that the action of cstmt.getMoreResults() closes any open result sets before moving to the next one. What you are ending up with is an arraylist of closed ResultSet objects. When you try to read from them, you get the error saying "result set is already closed"
from the java docs
boolean getMoreResults()
throws SQLException
Moves to this Statement object's next result, returns true if it is a
ResultSet object, and implicitly closes any current ResultSet
object(s) obtained with the method getResultSet.

use one jdbc connection class for all classes java

i have been using this JDBC conection in all of my class that had to run query but i created a new class which i dont want the constructor with a parameter of the DConnection from JDBC Class(main Database Class).
but i keep on getting NullPointExceptions. Can anyway figur out what that problem may be.
Thanks.
public class UsersDao {
// associating the Database Connection objekt
private DConnector connector;
private final Connection myConn;
// Constructor
public UsersDao() throws CZeitExceptionHand,SQLException {
myConn = connector.getConnenction();
}
public boolean updateUsers(String mitarb, int mid) throws SQLException{
// PreparedStatement myStmt = null;
Statement stmt = myConn.createStatement();
try {
String myStmt = "SELECT Bly "
+ "" + mid + ";";
return stmt.execute(myStmt);
} finally {
close(stmt);
}
}
Example like this Method which is working but in different class
String[][] getAllTheWorkers(DConnector connector) throws CZeitExceptionHand {
try {
Connection connect = connector.getConnenction();
Statement stmt = connect.createStatement();
ResultSet result = stmt.executeQuery("SELECT ");
result.last();
int nt = result.getRow();
result.beforeFirst();
}
return results;
} catch (SQLException e) {
throw new CZeitExceptionHand("Error: " + e);
}
}
The object does not seem to be initialized.
Can you please post which method is not working and from where it is invoked ?
P.S : Unable to add a comment - that is why have answered !

connecting Java to MySQL

I'm doing my dissertation on software engineering and im building a small application that makes use of a SQL DB, in this case MySQL. I'm also using the application controller pattern. So the code I have working for retrieving data from the db is;
public static void main(String[] args)
{
try
{
String url = "jdbc:mysql://localhost:3306/tm470_returns_stock_management_system";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"root","root");
Statement st = con.createStatement();
ResultSet res = st.executeQuery("SELECT * FROM test_table");
while (res.next())
{
int id = res.getInt("test_id");
String msg = res.getString("test_info");
System.out.println(id + "\t" + msg);
}
con.close();
}
catch(Exception e)
{
System.out.println("DB connection unsuccesful");
}
}
I now want to transfer this out of my Main class/string and into my Application Controller Class (which is called Facility).
Now my question is, for every method in my Facility Class that needs to access the DB, do i have to do the full code each time? Or can i create a method within the Facility class that each application method can just call whenever it needs to access the DB. If i can condense all this into a method, can you advise me how to go about it please?
Be gentle with me guys, I am a learner :)
How about adding a utility class like ConnectionUtil and using the static method to access the connection.
import java.sql.Connection;
import java.sql.DriverManager;
public class ConnectionUtil{
static final String url = "jdbc:mysql://localhost:3306/";
static final String dbName = "test";
static final String driver = "com.mysql.jdbc.Driver";
static final String userName = "userparatest";
static final String password = "userparatest";
Connection con = null;
static Connection getConnection() throws Exception {
if(con == null)
{ Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + dbName, userName,password);
}
return con;
}
}
this can be further improved but just providing a start..
just call below whenever you want a statement..
Statement st = ConnectionUtil.getConnection().createStatement();
I would map it as a own class, which is used by your application other classes. When you define it as a singleton you will only need one instance in your complete application
Yes , you can write a method for accessing db and you can reuse it across all the applications.
Keep the following in a method and reuse it.
String url = "jdbc:mysql://localhost:3306/tm470_returns_stock_management_system";
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(url,"root","root");
Statement st = con.createStatement();
int productID = 6;
String skuCode = "ABC123";
ResultSet res = st.executeQuery("SELECT * FROM test_table");
while (res.next())
{
int id = res.getInt("test_id");
String msg = res.getString("test_info");
System.out.println(id + "\t" + msg);
}

How to use the mysql connection on multiple classes?

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

Categories