The error is that I cant open the connection to mysql database, it must be an error in parameters but I am confused , I have no idea where is the problem.
-
You need to download the MySQL JDBC from Oracle's website here: https://dev.mysql.com/downloads/connector/j/ and add it to your project. – Jake Miller Dec 27 '16 at 18:14
-
Could be a possible [duplicate](http://stackoverflow.com/questions/5556664/how-to-fix-no-suitable-driver-found-for-jdbcmysql-localhost-dbname-error-w) – Kulasangar Dec 27 '16 at 18:16
-
refer this link http://stackoverflow.com/questions/2839321/connect-java-to-a-mysql-database – Teja Dec 27 '16 at 18:24
-
ok thank you all i will try now – M.AbouJamra Dec 27 '16 at 19:06
2 Answers
First you need to create a MySQL schema. Secondly, use JDBC to connect to your recently created database (via localhost - make sure you get the user/password right).
After that you should use DAO-like classes. I'll leave here a Connect class:
public class Connect {
private static final String USERNAME = "root";
private static final String PASSWORD = "12345";
private static final String URL = "localhost";
private static final String SCHEMA = "new_schema";
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection connect() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://"+URL+"/"+SCHEMA+"?user="+USERNAME+"&password="+PASSWORD);
}
}
After you have the Connect class, you should connect to the database using Connection c = Connect.connect(). Here's a class that implements it.
public static List<Album> list() throws SQLException {
Connection c = Connect.connect();
ResultSet rs = c.createStatement().executeQuery("SELECT * FROM Albums");
List<Album> list = new ArrayList<>();
while (rs.next()) {
String name = rs.getString("nome"); // first table column (can also use 1)
String artist = rs.getString("artista"); // second table column (can also use 2)
Album a = new Album(name, artist);
list.add(a);
}
return list;
}
It should also give you an insight as to how you should use SQL commands.
If you'd like a more in-depth help you should post the code you used, otherwise it's difficult to give you a more "to-the-point" explanation.
- 19
- 2
JDBC URLs can be confusing. Suggest you try using a SQL tool that understands the JDBC protocol (such as the database development perspective in Eclipse) to validate the URL and make sure you can connect to the database before you start coding. Cutting and pasting a URL known to work into your code can avoid many problems.
- 201
- 2
- 4