gpt4 book ai didi

java - 这是在 JDBC (JAVA) 中执行查询的最简单方法吗

转载 作者:行者123 更新时间:2023-12-01 11:49:26 25 4
gpt4 key购买 nike

在学习 JDBC 的过程中,我创建了以下接口(interface)和类,以便将来使用时方便编程。我相信仍然有可能做得比这更简单。我的程序所做的是通过提供查询字符串来获取结果,而不是执行加载驱动程序类、创建 Connection 和 Statement 对象并从中获取结果等所有过程。将来是否有更简单的方法来做到这一点并增强功能?

MyConnection.java----接口(interface)

package com.cherukuri.jdbc;

import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public interface MyConnection {

public static String DRIVER = "com.mysql.jdbc.Driver";
public static String DB_URL = "jdbc:mysql://localhost:3305/STUDENTS";
public static String USER = "root";
public static String PASSWORD = “********";

default void loadDriver() {

try {
Class.forName(DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
}

public Connection getConnection();

public Statement getStatement();
}

DataBaseConnection.java

package com.cherukuri.jdbc;

import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;

public class DataBaseConnection implements MyConnection {

Connection connection = null;
Statement statement = null;

@Override
public Connection getConnection() {
try {
connection = (Connection) DriverManager.getConnection(DB_URL, USER,
PASSWORD);
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return connection;
}

@Override
public Statement getStatement() {
connection = getConnection();
try {
statement = (Statement) connection.createStatement();
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}
return statement;
}

public ResultSet runQuery(String Query) {

ResultSet resultSet = null;

statement = getStatement();
try {
resultSet = statement.executeQuery(Query);
} catch (SQLException e) {
System.out.println(e.getMessage());
e.printStackTrace();
}

return resultSet;

}

}

TestBaseConnection.java

package com.cherukuri.jdbc;

import java.sql.ResultSet;
import java.sql.SQLException;

public class TestDataBaseConnection {

public static void main(String[] args) {

DataBaseConnection dbcon = new DataBaseConnection();

ResultSet rs = dbcon.runQuery("Select * from tblStudent");
try {
while (rs.next()) {
System.out.println(rs.getInt(1) + " ------------------- "
+ rs.getString(2));
}
} catch (SQLException e) {
e.printStackTrace();
}

}
}

最佳答案

您可以尝试Spring JDBC它以类似于包装类的方式简化了 JDBC 访问。它消除了对一些 bolierplate 代码的需要,并为您管理数据库连接。

关于java - 这是在 JDBC (JAVA) 中执行查询的最简单方法吗,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28913567/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com