This blog is about providing theory as well as simple executable codes of different programming languages such as java, C, C++, and web programming, etc. This blog will be helpful to the IT students to learn about programming.

Thursday, March 9, 2023

Write a JDBC connection program with following details. a. Driver: com.mysql.jdbc.Driver. b. Host: localhost: c. Database: students d. User:root e. Password: secret f. Port: 3306

 Here's an example JDBC connection program in Java that uses the MySQL JDBC driver and connects to a database with the provided details:

import java.sql.*;
public class JdbcConnectionExample {
    public static void main(String[] args) {
        // JDBC driver and database URL
        String jdbcDriver = "com.mysql.jdbc.Driver";
        String dbUrl = "jdbc:mysql://localhost:3306/students";
        
        // Database credentials
        String user = "root";
        String password = "secret";
        
        // Establish connection to database
        Connection conn = null;
        try {
            // Register JDBC driver
            Class.forName(jdbcDriver);
            
            // Open a connection
            conn = DriverManager.getConnection(dbUrl, user, password);
            
            // Do something with the connection
            // ...
            
            // Close the connection
            conn.close();
        } catch (SQLException se) {
            // Handle errors for JDBC
            se.printStackTrace();
        } catch (Exception e) {
            // Handle errors for Class.forName
            e.printStackTrace();
        } finally {
            // Close the connection
            try {
                if (conn != null) {
                    conn.close();
                }
            } catch (SQLException se) {
                se.printStackTrace();
            }
        }
    }
}

This program uses the com.mysql.jdbc.Driver JDBC driver and connects to a MySQL database at localhost:3306/students with the username root and password secret. After establishing a connection, you can execute SQL queries and perform other database operations using the Connection object. Finally, the connection is closed in a finally block to ensure that it is properly released.

No comments:

Post a Comment

If you have any doubts, please let me know

Slider Widget