Java MySQL与ArrayLists的集成

我试图让我的程序能够运行多次运行。 这意味着如果我在我的程序中输入一些内容然后将其关闭,当我重新启动它时,在MySQL的帮助下仍然存在这些信息。 我是Java和MySQL的新手,但这非常重要。 我的程序运行完美,但我不知道如何让MySQL保持arraylist。 我已经将数据库设置为我需要的一切。 到目前为止,这是我的MySQL桥:

import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; public class SQL { Class.forName("com.mysql.jdbc.Driver"); Connection con = DriverManager.getConnection("jdbc:mysql://instance23389.db.xeround.com:15296/Inventory","user","password"); PreparedStatement Statement = con.prepareStatement("Select * from name"); ResultSet result = Statement.executeQuery(); { while(result.next()) { } } } 

这一行:

  Class.forName("com.mysql.jdbc.Driver"); throws "Syntax error on token ""com.mysql.jdbc.Driver"", delete this token" 

我已经为网桥导入了正确的文件。

我也尝试了以下代码。 它运行时没有错误,但它没有从数据库导入信息。 我从哪里去?

 public static void main(String[] args) throws SQLException { Connection con = DriverManager.getConnection("jdbc:mysql://instance23389.db.xeround.com:15296/Inventory","user","password"); PreparedStatement Statement = con.prepareStatement("Select * from inventory"); ResultSet result = Statement.executeQuery(); while(result.next()) { // do something with the row } @SuppressWarnings("resource") Scanner input = new Scanner(System.in); int x=0; int choice; do{ do { System.out.println("Please select what you would like to do:\n1 = Add New\n2 = Update Inventory\n3 = Lookup Inventory\n4 = Make Changes\n5 = Totals"); choice=input.nextInt(); if(choice5) { System.out.println("Please enter a number 1-5."); } else { } }while(choice5); if(choice==1) { Product_Chart.newInv(); } else if(choice==2) { Product_Chart.updateInv(); } else if(choice==3) { Product_Chart.lookupInv(); } else if(choice==4) { Product_Chart.MakeChanges(); } else if(choice==5) { Product_Chart.Totals();// TODO does not call Product_Chart.Totals(); } else { System.out.println("Error 101"); } }while(x==0); } } 

您需要将代码放在方法中。 试试这个,然后“运行”你的class级:

 public class SQL { public static void main(String[] args) throws SQLException { Connection con = DriverManager.getConnection("jdbc:mysql://instance23389.db.xeround.com:15296/Inventory","user","password"); PreparedStatement Statement = con.prepareStatement("Select * from name"); ResultSet result = Statement.executeQuery(); while(result.next()) { // do something with the row } } } 

如果你编写一个像这样的main方法( static ,with void return type和String[]参数),你就可以“运行”你的类。

注意这一行

 Class.forName("com.mysql.jdbc.Driver"); 

完全没必要:当您尝试打开连接时将加载驱动程序。

这个说法:

 Class.forName("com.mysql.jdbc.Driver"); 

位于类的顶层 – 您通常具有变量声明,方法或构造函数。 您可能希望将其放在静态初始化程序中:

 static { Class.forName(...); } 

……虽然我认为这一步在很长一段时间内都是不必要的。 (基本上,驱动程序发现过程有所改进。)

至于让MySQL“持有ArrayList” – 您需要插入,更新或删除数据库的内容以匹配您的数据。 在单个答案中涵盖的主题太宽泛,但您应该阅读有关如何修改数据以及仅选择它的教程。