JAVA; 如何使SQL的getConnection();成为主变量prime?

问题描述 投票:-1回答:1

我想问一下,如何使Connection con = getConnection();成为一个primer或main变量,使它不至于每次执行函数时都连接到SQL数据库。因为在我的代码中可以看到,每一个函数类都有Connection con = getConnection();,所以每一个函数都会连接到数据库。这使得我的程序处理得很慢。请大家帮忙谢谢。

package march30;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.Arrays;

public class sqltesting {

public static void main(String[] args) throws Exception {
    // TODO Auto-generated method stub
        get();
}

public static void lookup() throws Exception{
    try {
        Connection con = getConnection();
        PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename where id=6");
        ResultSet result = statement.executeQuery();

        if (result.next()) {
            System.out.println("First Name: " + result.getString("first"));
            System.out.println("Last Name: " + result.getString("last"));
            }
        else {
            System.out.println("No Data Found");
            }

    } catch (Exception e) {}        
}

public static ArrayList<String> get() throws Exception{
    try {
        Connection con = getConnection();
        PreparedStatement statement = con.prepareStatement("SELECT first,last FROM tablename");

        ResultSet result = statement.executeQuery();

        ArrayList<String> array = new ArrayList<String>();
        while (result.next()) {
            System.out.print(result.getString("first"));
            System.out.print(" ");
            System.out.println(result.getString("last"));

            array.add(result.getString("last"));
        }
        System.out.println("All records have been selected!");
        System.out.println(Arrays.asList(array));
        return array;

    } catch (Exception e) {System.out.println((e));}    
    return null;
}

public static void update() throws Exception{
    final int idnum = 2;
    final String var1 = "New";
    final String var2 = "Name";
    try {
        Connection con = getConnection();
        PreparedStatement updated = con.prepareStatement("update tablename set first=?, last=? where id=?");
        updated.setString(1, var1);
        updated.setString(2, var2);
        updated.setInt(3, idnum);
        updated.executeUpdate();
        } catch (Exception e) {System.out.println((e));}        
    finally{
        System.out.println("Update Completed");
        }
}

public static void delete() throws Exception{
    final int idnum = 7;
    try {
        Connection con = getConnection();
        PreparedStatement deleted = con.prepareStatement("Delete from tablename where id=?");
        deleted.setInt(1, idnum);
        deleted.executeUpdate();
        } catch (Exception e) {System.out.println((e));}        
    finally{
        System.out.println("Delete Completed");
        }
}

public static void post() throws Exception{
    final String var1 = "Albert";
    final String var2 = "Reyes";
    try {
        Connection con = getConnection();
        PreparedStatement posted = con.prepareStatement("INSERT INTO tablename (first, last) VALUES ('"+var1+"', '"+var2+"')");
        posted.executeUpdate();
    } catch (Exception e) {System.out.println((e));}        
    finally{
        System.out.println("Insert Completed");
        }
}

public static void createTable() throws Exception {
    try {
        Connection con = getConnection();
        PreparedStatement create = con.prepareStatement("CREATE TABLE IF NOT EXISTS tablename(id int NOT NULL AUTO_INCREMENT, first varchar(255), last varchar(255), PRIMARY KEY(id))");
        create.executeUpdate();
    } catch (Exception e) {System.out.println((e));}
    finally{
        System.out.println("Function Completed");
        }
}

public static Connection getConnection() throws Exception{
    try {
        String driver = "com.mysql.cj.jdbc.Driver";
        String url = "jdbc:mysql://xxxxxxxx.amazonaws.com:3306/pointofsale";
        String username = "xxxxx";
        String password = "xxxxxx";
        Class.forName(driver);

        Connection conn = DriverManager.getConnection(url,username,password);
        return conn;
    } catch (Exception e)   {System.out.println(e);}        

    return null;
}
}
java mysql main
1个回答
1
投票

为了解决你的问题,你需要在你的sqltesting类中存储一个Connection对象作为类成员。然后你需要引用Connection对象而不是getConnection()。值得一提的是,Connection是一个AutoClosable对象,所以当你使用完这个资源后,你需要关闭它,也就是在应用程序处理时。你也可以考虑使用Hikari或C3P0这样的连接池API,这样你就可以在需要的时候打开和关闭连接,而不是让1个连接长时间打开。

class SQLTesting {

    private final Connection connection;

    public SQLTesting(Connection connection) {
        this.connection = connection;
    } 

    public SQLTesting() {
        this(getConnection());
    }

    // other methods

    private Connection getConnection() {
        // your method to create connection, rename to createConnection maybe. 
    }
}
© www.soinside.com 2019 - 2024. All rights reserved.