我必须在同一个类的不同方法中执行多个SQL查询。有没有办法让这些语句通用,我可以在所有方法中使用相同的con,statement变量来执行查询。
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection ("jdbc:mysql://localhost:3306/kamal","root","root");
Statement statement=con.createStatement();
答案 0 :(得分:5)
在课堂上使用此方法并反复调用
public Connection getMyConnection() throws ClassNotFoundException, SQLException
{
String connectionURL = "jdbc:mysql://localhost:3306/test";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(connectionURL, "root", "root");
return con;
}
答案 1 :(得分:3)
您可以使用静态方法编写连接语句,该方法可以在其他类中重复使用:
public Connection getConnection() throws ClassNotFoundException, SQLException {
String connURL = "jdbc:mysql://localhost:3306/test";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(connURL, "username", "password");
return con;
}
但是这有一个缺点,你必须手动管理数据库连接的打开和关闭。
为了缓解上述缺点,请考虑使用像Hibernate这样的对象关系映射框架,它将连接细节抽象为将重新用于每个数据库连接的设置文件。
答案 2 :(得分:1)
如果您需要整个班级中的变量,您可能希望将其变为成员变量。
但是,对于像Connections
这样的资源不鼓励这样做,因为它可以轻易地剥夺系统,并增加额外的负载。
您可以使用名为Singleton
的设计模式。阅读它here。
基本上,您可以使用此实现创建一个名为ConnectionManager
的新类
class ConnectionManager {
private static ConnectionManager _instance = null;
private Connection con = null;
protected ConnectionManager() {
//empty
}
private void init() {
Class.forName("com.mysql.jdbc.Driver").newInstance();
this.con = DriverManager.getConnection
("jdbc:mysql://localhost:3306/kamal","root","root");
}
public Connection getConnection() {
return this.con;
}
public static ConnectionManager getInstance() {
if(_instance == null) {
_instance = new ConnectionManager();
_instance.init();
}
return _instance;
}
}//end class
现在,这可以通过多种方式帮助我们,特别是如果您的应用程序是多线程的。我们只需要建立一个连接,除非程序已被终止,否则它将保持不变。无论你需要创建一个新的Statement
,你都可以使用它。
ConnectionManager.getInstance().getConnection().createStatement();
答案 3 :(得分:1)
这是一个非常天真的连接池实现。请注意,这是使用记事本编写的,尚未经过测试:
public interface ConnectionPool {
public Connection getConnection() throws SQLException;
public void closeConnection(Connection connection) throws SQLException;
}
public class MySQLConnectionPool implements ConnectionPool {
private static final Class<?> mysqlDriver;
private final Stack<Connection> connections;
private final String url;
private final String user;
private final String password;
private final int maxSize;
static {
mysqlDriver = Class.forName("com.mysql.jdbc.Driver");
}
public MySQLConnectionPool(String url, String user, String password, int initialSize, int size) {
if (initialSize > size) {
throw new IllegalArgumentException("Pool initial size must not be greater than size");
}
if (size <= 0) {
throw new IllegalArgumentException("Pool size must be greater than zero");
}
this.size = maxSize;
this.url = url;
this.user = user;
this.password = password;
this.connections = new Stack<Connection>();
try {
for (int i = 0;i < initialSize;i++) {
connections.push(getConnection(url, user, password));
}
} catch (Exception exception) {
// TODO: Log somewhere?
}
}
public Connection getConnection(String url, user, password) throws SQLException {
DriverManager.getConnection(url, user, password);
}
public Connection getConnection() SQLException {
try {
synchronized (connections) {
return connections.pop();
}
} catch (EmptyStackException exception) {
return getConnection(url, user, password);
}
}
public void closeConnection(Connection connection) throws SQLException {
synchronized (connections) {
if (connections.size() < maxSize) {
connections.push(connection);
return;
}
}
connection.close();
}
}
public class SingletonMYSQLConnectionPool extends MySQLConnectionPool() {
private static volatile SingletonMYSQLConnectionPool instance;
private SingletonMYSQLConnectionPool() {
super("jdbc:mysql://localhost:3306/kamal","root","root", 0, 2);
}
public static SingletonMYSQLConnectionPool getInstance() {
if (instance == null) {
synchronized (SingletonMYSQLConnectionPool.class) {
if (instance == null) {
instance = new SingletonMYSQLConnectionPool();
}
}
}
return instance;
}
}
答案 4 :(得分:0)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
PrintWriter pw = response.getWriter();
Connection conn;
try
{
String fname = request.getParameter("fname");
String lname = request.getParameter("lname");
Class.forName("com.mysql.jdbc.Driver");
conn = (Connection)DriverManager.getConnection("jdbc:mysql://localhost:3307/soft\",\"root\",\"root");
PreparedStatement pst = (PreparedStatement) conn.prepareStatement("insert into soft.IT(fname,lname) values(?,?)");
pst.setString(1,fname);
pst.setString(2,lname);
int i = pst.executeUpdate();
if(i!=0){
pw.println("<br>Record has been inserted");
}
else
{
pw.println("failed to insert the data");
}
}catch (Exception e)
{
pw.println(e);
}
}
答案 5 :(得分:-1)
在数据库中创建存储过程。