如何从VPS连接MariaDB数据库?环境及代码异常求助
Hey there, let's fix your MariaDB connection issue step by step!
1. Fix Database User Permissions First
Your current database user admin@localhost is restricted to only local connections on the VPS. To connect remotely from NetBeans, you need to grant remote access permissions to this user:
- Log into your VPS's MariaDB console, then run these SQL commands:
-- Grant access from any IP (replace % with your local IP for tighter security) GRANT ALL PRIVILEGES ON *.* TO 'admin'@'%' IDENTIFIED BY 'your_database_password'; FLUSH PRIVILEGES;
2. Correct Your JDBC Connection String
Your existing connection string is incomplete. Using your provided server details, here's the full, valid format:
// Replace placeholders with your actual database name and password String dbUrl = "jdbc:mariadb://digiblogs.info:2017/your_database_name?useUnicode=true&characterEncoding=utf8"; Connection connect = DriverManager.getConnection(dbUrl, "admin", "your_database_password");
Key details included:
- VPS hostname:
digiblogs.info - Custom port:
2017 - Character set matching your server:
utf8
3. Simplify Driver Loading (Optional)
From JDBC 4.0 onwards, the MariaDB driver loads automatically—you can safely remove this line from your code:
Class.forName("org.mariadb.jdbc.Driver").newInstance();
If you keep it, double-check the class name is spelled correctly (it looks right in your snippet!).
4. Verify VPS Firewall & Network Settings
- Make sure your VPS firewall allows inbound traffic on port
2017. For Ubuntu/Debian systems using UFW, run:
ufw allow 2017/tcp ufw reload
- Check your MariaDB config file (usually
/etc/mysql/mariadb.conf.d/50-server.cnf) and ensurebind-addressis set to0.0.0.0(allows all IPs) or your local machine's public IP.
Full Working Test Code
Here's a complete, runnable example to validate the connection:
import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; public class MariaDBConnectionTest { public static void main(String[] args) { String dbUrl = "jdbc:mariadb://digiblogs.info:2017/your_database_name?useUnicode=true&characterEncoding=utf8"; String username = "admin"; String password = "your_database_password"; try (Connection connection = DriverManager.getConnection(dbUrl, username, password)) { if (connection != null) { System.out.println("Successfully connected to MariaDB! 🎉"); } } catch (SQLException e) { System.err.println("Connection failed: " + e.getMessage()); } } }
Quick Double-Check
Ensure the mariadb-java-client-2.2.3.jar is properly added to your NetBeans project: right-click your project → Properties → Libraries → Add JAR/Folder, then select the downloaded jar file.
内容的提问来源于stack exchange,提问作者kien vu

