Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/352.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 使用JDBC创建用于查询MySQL表的抽象类或接口_Java_Mysql_Database_Jdbc - Fatal编程技术网

Java 使用JDBC创建用于查询MySQL表的抽象类或接口

Java 使用JDBC创建用于查询MySQL表的抽象类或接口,java,mysql,database,jdbc,Java,Mysql,Database,Jdbc,我正在实现一个对mysql数据库进行基本查询的应用程序, e、 g.更新、插入、删除。 我想知道当事情发生时,是否有人像我一样偏执 为了连接查询字符串,他们编写了抽象方法 要做到这一点,它可以在所有表上工作,并避免容易的打字错误 这是我避免串联中严重错误的方法,但我希望 看看其他人也做了些什么来拓宽我的思路 这是我在伪代码中的方法 假设我有一个名为ACC的mysql表,其中包含以下列: acc_no (primary key) | acc_first_name | acc_last_name

我正在实现一个对mysql数据库进行基本查询的应用程序, e、 g.更新、插入、删除。 我想知道当事情发生时,是否有人像我一样偏执 为了连接查询字符串,他们编写了抽象方法 要做到这一点,它可以在所有表上工作,并避免容易的打字错误

这是我避免串联中严重错误的方法,但我希望 看看其他人也做了些什么来拓宽我的思路

这是我在伪代码中的方法

假设我有一个名为ACC的mysql表,其中包含以下列:

acc_no (primary key) | acc_first_name |  acc_last_name 
123                  |John            | Smith   
然后我实现了一个java抽象类

public abstract class Acc{
  // All column values in the table Acc as constants
  public static final String NUM = "acc_no";
  public static final String FIRST_NAME = "acc_first_name";
  public static final String LAST_NAME = "acc_last_name";

  private Hashtable<String, String> hash = new Hashtable<String, String>();

  public Acc(Connection con, String acc_no){
    // Get values from mysql
    PreparedStatement pstmt = ...SELECT * FROM ACC where ACC_NO = acc_no ....
    ResultSet rs = resultset from pstmt

    //Then put all the resultset rs values in hash so the hashtable have key/values             
    //that look something like this:
    //[[NUM, "123"]
    // [FIRST_NAME, "John"]
    // [LAST_NAME, "Smith"]]
    // The key is one of the constants in this class
    // and the corresponding values are taken from mysql database
  }


  public String get(String column){
    return hash.get(column)
  }
}

你考虑过像Hibernate这样的ORM吗?它为您做了类似的事情。不要这样做,只使用DTO/DAO模式。我不确定您在concatation方面有什么问题,但如果是关于在查询条件中连接值,那么使用PreparedStatement进行参数化查询。谢谢ryan1234!我要是早点知道就好了!Mark Rotterveel,您使用preparedstatement使用参数化查询是什么意思,您能举个例子吗?谢谢我更喜欢串联,因为它是1。容易犯语法错误,例如忘记加引号、忘记空格、拼写错误2。它不是面向对象的,因此妨碍了充分利用java功能的能力
class AccApp extends Acc{

   AccApp(Connection con){
     super(con, "123")
     printName(); 
   }

   String printName(){
      // Notice that I use static constants to get the column values
      // instead of typing this.get("acc_first_name") and this.get("acc_last_name")
      System.out.println(this.get(Acc.FIRST_NAME) + this.get(Acc.LAST_NAME));
   }

}