To establish a JDBC connection in NetBeans (for a MySQL database), follow these step-by-step instructions:
✅ Step 1: Add JDBC Driver to Your Project
-
Download MySQL Connector/J from https://dev.mysql.com/downloads/connector/j/.
-
In NetBeans, right-click your project > Properties.
-
Go to Libraries > Click Add JAR/Folder.
-
Browse and select the
mysql-connector-java-x.x.xx.jar
file.
✅ Step 2: Write JDBC Code in Java
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class DBConnection {
public static void main(String[] args) {
String url = "jdbc:mysql://localhost:3306/your_database_name";
String user = "your_username";
String password = "your_password";
try {
// Load the MySQL JDBC driver (optional from Java 6+)
Class.forName("com.mysql.cj.jdbc.Driver");
// Establish connection
Connection conn = DriverManager.getConnection(url, user, password);
System.out.println("Connection successful!");
// Close connection
conn.close();
} catch (ClassNotFoundException e) {
System.out.println("MySQL JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Connection failed.");
e.printStackTrace();
}
}
}
✅ Step 3: Run Your Program
-
Right-click your Java file > Run File.
-
Check output:
"Connection successful!"
if successful.
🔧 Notes:
-
Use
com.mysql.cj.jdbc.Driver
for MySQL 8+. -
Make sure your MySQL server is running and accessible.
-
Replace
localhost
,your_database_name
,your_username
, andyour_password
with actual credentials.
Would you like an example using PreparedStatement for a simple insert or select query?
0 Comments