我这里遇到一个小问题。 基本上我想使用一个类创建一个到数据库的连接池。其他类可以使用该池来执行查询。我已经将其他类作为连接类的子类。 这是我到目前为止所拥有的。
Connection类/(连接池类)
import java.sql.*; public class connect extends cPool {
public static void main(String[] args) {
cPool en = new cPool(); //crate an object in the name of cPoll calss
Connection conn = null;
Object data;
data = (connect) conn;
en.readinfo(); //call object then method name
String userName = "root";
String password = "" + en.paword + "";// hold outside try catch block to get and set
String url = "" + en.url + "";
try
{
Class.forName ("com.mysql.jdbc.Driver").newInstance ();
conn = DriverManager.getConnection (url, userName, password);
System.out.println ("Database connection established");
}
catch (Exception e)
{
System.err.println ("Cannot connect to database server");
System.err.println("Tried connecting using" + url + userName + password +"");
}
finally
{
}
}
}
这里是执行语句类
import java.sql.*;
import java.util.logging.Level;
import java.util.logging.Logger;
public class getProduct extends connect {
public static void main(String[] args) {
connect cn = new connect();
Connection conn = cn.data;
try {
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM My_Table");
}
catch (SQLException ex) {
Logger.getLogger(getProduct.class.getName()).log(Level.SEVERE, null, ex);
}
finally
{
}
}
}
我无法执行任何语句。从第二堂课开始,当我这样做时,我收到 createStatement() 错误。它说“无法编译源代码 - 找不到符号” 非常感谢。
最佳答案
连接池是一个高级主题,从您的代码来看,我想说暂时先休息一下,先学习一些 Java 基础知识。因此,也许您应该使用现有的解决方案:
关于Java 连接到数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6042261/