javafx 连接数据库
时间: 2023-07-05 20:31:54 浏览: 151
要在JavaFX中连接数据库,可以使用JDBC API。以下是连接到MySQL数据库的示例代码:
```java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DatabaseConnection {
private static final String DB_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_CONNECTION = "jdbc:mysql://localhost:3306/your_database_name";
private static final String DB_USER = "your_database_user";
private static final String DB_PASSWORD = "your_database_password";
public static Connection getDBConnection() {
Connection dbConnection = null;
try {
Class.forName(DB_DRIVER);
} catch (ClassNotFoundException e) {
System.out.println(e.getMessage());
}
try {
dbConnection = DriverManager.getConnection(DB_CONNECTION, DB_USER, DB_PASSWORD);
return dbConnection;
} catch (SQLException e) {
System.out.println(e.getMessage());
}
return dbConnection;
}
}
```
在这个示例中,我们使用JDBC连接到MySQL数据库。要连接到不同的数据库,只需要更改DB_DRIVER,DB_CONNECTION,DB_USER和DB_PASSWORD变量,然后使用getDBConnection()方法获取数据库连接对象。
阅读全文