I am trying to get my program to be able to run over multiple runs. Meaning if I input something in my program and then shut it down, when I start it back up that info will still be there with the help of MySQL. I am fairly new to Java and MySQL but this is very important.
My program works perfectly but I have no idea how to get MySQL to hold the arraylist. I already have the database set up with everything I need. This is my MySQL bridge so far:
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())
{
}
}
}
and this line:
Class.forName("com.mysql.jdbc.Driver");
throws "Syntax error on token ""com.mysql.jdbc.Driver"", delete this token"
and I have already imported the correct files for the bridge.
I also tried the following code. It runs with no errors but it isn't importing the info from the database. Where do I go from there?
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(choice<1 || choice>5)
{
System.out.println("Please enter a number 1-5.");
}
else
{
}
}while(choice<1 || choice>5);
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);
}
}
解决方案
This statement:
Class.forName("com.mysql.jdbc.Driver");
is at the top level of the class - where you'd normally have variable declarations, methods, or constructors. You might want to put it in a static initializer:
static {
Class.forName(...);
}
... although I thought that this step had been unnecessary for quite some time. (The driver discovery process has improved, basically.)
As for getting MySQL to "hold the ArrayList" - you need to insert, update or delete the contents of the database to match your data. It's too broad a topic to cover in a single answer, but you should read tutorials about how to modify data as well as just selecting it.