因此,我正在使用Java Eclipse制作JDBC CRUD程序,并且为了防止数据泄漏,我无法确定何时以及如何关闭连接。在其他情况下,我想问一下我的程序是否在每个函数中都打开了连接,这使得连接不太理想。以下是我的代码,
_getConnection代码建立数据库连接,
package com.Database;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class _getConnection {
static final String JDBC_Driver = "com.mysql.jdbc.Driver";
static final String URL = "jdbc:mysql://localhost:3306/rubyrail?useSSL=false";
static final String Username = "root";
static final String Password = "root";
static Connection connection = null;
public Connection connect()
{
//Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(URL, Username, Password);
}
catch(Exception e)
{}
return connection;
}
public static Connection close()
{
if (connection!=null)
{
try {
connection.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
return connection;
}
}
Database_Connection是CRUD应用程序,
package com.Database;
import java.sql.*;
import java.sql.Date;
import java.util.*;
public class Database_Connection
{
static Scanner scanner = new Scanner(System.in);
public static void Create()
{
_getConnection get_connect = new _getConnection();
Connection conn = get_connect.connect();
int item_no = 0;
String item_name = null;
int item_cost = 0;
Statement stmt = null;
System.out.println("\nEnter the following details,");
System.out.println("\nItem Number: ");
item_no = scanner.nextInt();
scanner.nextLine();
System.out.println("\nItem Name: ");
item_name = scanner.nextLine();
System.out.println("\nItem Cost: ");
item_cost = scanner.nextInt();
try
{
String sql = "Insert into item (item_no, item_name, item_cost, last_update) values ("+item_no+",'"+item_name+"',"+item_cost+",CURDATE())";
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
//stmt.execute(sql);
}
catch(Exception e)
{System.out.println(e);}
}
public static void Read()
{
_getConnection get_connect = new _getConnection();
Connection conn = get_connect.connect();
Statement stmt=null;
try
{
String sql = "Select * from item";
stmt = conn.prepareStatement(sql);
ResultSet resultset = stmt.executeQuery(sql);
while (resultset.next())
{
int item_no = resultset.getInt("item_no");
String item_name = resultset.getString("item_name");
int item_cost = resultset.getInt("item_cost");
Date last_update = resultset.getDate("last_update");
System.out.print("Item Number: " + item_no);
System.out.print(", Item Name: " + item_name);
System.out.print(", Item Cost: " + item_cost);
System.out.println(", Last Updated: " + last_update);
}
}
catch(Exception e)
{System.out.println(e);}
}
public static void Update()
{
_getConnection get_connect = new _getConnection();
Connection conn = get_connect.connect();
Statement stmt=null;
int item_no = 0;
String item_name = null;
int item_cost = 0;
System.out.println("\nEnter the Item Number to be Updated,");
System.out.println("\nItem Number: ");
item_no = scanner.nextInt();
scanner.nextLine();
System.out.println("\nEnter the following details,");
System.out.println("\nItem Name: ");
item_name = scanner.nextLine();
System.out.println("\nItem Cost: ");
item_cost = scanner.nextInt();
try
{
String sql = "update item set item_name = '"+item_name+"',item_cost ="+item_cost+",last_update = CURDATE() where item_no = "+item_no;
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
}
catch(Exception e)
{System.out.println(e);}
}
public static void Delete()
{
_getConnection get_connect = new _getConnection();
Connection conn = get_connect.connect();
Statement stmt=null;
int item_no = 0;
System.out.println("\nEnter the Item Number to be Deleted,");
System.out.println("\nItem Number: ");
item_no = scanner.nextInt();
try
{
String sql = "delete from item where item_no = "+item_no;
stmt = conn.prepareStatement(sql);
stmt.executeUpdate(sql);
}
catch(Exception e)
{System.out.println(e);}
}
public static void Close()
{
_getConnection.close();
System.out.println("Closing Connection..");
System.out.println("Connection Closed!");
}
public static void main (String args[])
{
_getConnection get_connect = new _getConnection();
Connection conn = get_connect.connect();
int choice= 0;
try {
if(conn!=null)
while (choice < 6)
{
System.out.println("\n1. Create");
System.out.println("\n2. Read");
System.out.println("\n3. Update");
System.out.println("\n4. Delete");
System.out.println("\n5. Close");
choice = scanner.nextInt();
switch(choice)
{
case 1: Create();
break;
case 2: Read();
break;
case 3: Update();
break;
case 4: Delete();
break;
case 5: Close();
break;
}
}
}
catch (Exception e) {}
}
}
我希望我的解决方案在程序的Close()函数中具有结束位置。
答案 0 :(得分:0)
关闭数据库连接始终是最佳实践。
您可以添加一个finally
块以关闭数据库连接。最佳做法是按以下顺序关闭连接
ResultSet, Statement, and Connection
在程序末尾的finally块中。
请点击此链接以获取更多详细信息[接受的答案] https://stackoverflow.com/a/2225275/7719903
答案 1 :(得分:0)
您可以将代码更改为:
public class DatabaseConnection {
static final String URL = "jdbc:mysql://localhost:3306/rubyrail?useSSL=false";
static final String Username = "root";
static final String Password = "root";
private static Connection createConnection() {
return DriverManager.getConnection(URL, Username, Password);
}
public static void create() {
try (Connection connection = createConnection()) {
// do something with the connection
} catch (SQLException e) {
e.printStackTrace();
// or something else to handle the error
}
}
// same for the rest of your methods
public static void main (String args[]) {
int choice= 0;
while (choice < 6) {
System.out.println("\n1. Create");
System.out.println("\n2. Read");
System.out.println("\n3. Update");
System.out.println("\n4. Delete");
System.out.println("\n5. Close");
choice = scanner.nextInt();
switch(choice) {
case 1:
create();
break;
// other cases
}
}
}
}
这将为每个方法调用创建一个连接,这可能会降低效率,但会简化资源管理。如果性能至关重要,则应考虑使用提供连接池的数据源(例如HikariCP,Apache DBCP等)。使用连接池将允许连接的重用,而您的代码不必担心除了设置数据源配置之外的其他事情。
或者,在主连接中创建一次连接,并将其传递给您要调用的每个方法:
public static void create(Connection connection) {
try {
// do something with connection
} catch (SQLException e) {
e.printStackTrace();
// or something else to handle the error
}
}
public static void main (String args[]) {
try (Connection connection = createConnection()) {
int choice= 0;
while (choice < 6) {
System.out.println("\n1. Create");
System.out.println("\n2. Read");
System.out.println("\n3. Update");
System.out.println("\n4. Delete");
System.out.println("\n5. Close");
choice = scanner.nextInt();
switch(choice) {
case 1:
create(connection);
break;
// other cases
}
}
} catch (SQLException e) {
e.printStackTrace();
// or something else to handle the error
}
}