How to use the mysql connection on multiple classes?

丶灬走出姿态 提交于 2019-12-25 02:48:17

问题


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 .


回答1:


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.




回答2:


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 !!!




回答3:


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




回答4:


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...




回答5:


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


来源:https://stackoverflow.com/questions/20587996/how-to-use-the-mysql-connection-on-multiple-classes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!