最佳答案
首先,您需要创建一个MySQL模式。其次,使用JDBC连接到您最近创建的数据库(通过localhost-确保正确使用用户名/密码)。
之后,您应该使用类似DAO的类。我将在此处离开Connect类:
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);
}
}
在拥有Connect类之后,应该使用Connection c = Connect.connect()连接到数据库。这是实现它的类。
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;
}
它还应该使您了解如何使用SQL命令。
如果您想获得更深入的帮助,则应发布所使用的代码,否则很难为您提供更“直接的”解释。
关于java - 我如何从Java连接到mysql服务器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41350125/