task 8

PHOTO EMBED

Fri Nov 01 2024 15:43:59 GMT+0000 (Coordinated Universal Time)

Saved by @sem

package task8;

import java.sql.*;

public class jdbcex {
    // Database credentials and URL
    static final String JDBC_URL = "jdbc:mysql://localhost:3306/varshitha"; // Replace with your database name
    static final String JDBC_USER = "root"; // Replace with your MySQL username
    static final String JDBC_PASSWORD = "root"; // Replace with your MySQL password

    public static void main(String[] args) {
        try {
            // Load the MySQL JDBC driver
            Class.forName("com.mysql.cj.jdbc.Driver");

            // Establish the connection
            Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USER, JDBC_PASSWORD);
            System.out.println("Connected to the database.");

            // Create a statement object to execute SQL commands
            Statement statement = connection.createStatement();

            // SQL query to create a table named "Students"
            String createTableSQL = "CREATE TABLE IF NOT EXISTS Students (" +
                                    "id INT AUTO_INCREMENT PRIMARY KEY, " +
                                    "name VARCHAR(50) NOT NULL, " +
                                    "age INT, " +
                                    "grade VARCHAR(10)" +
                                    ");";

            // Execute the SQL command to create the table
            statement.executeUpdate(createTableSQL);
            System.out.println("Table 'Students' created successfully.");

            // Close the statement and connection
            statement.close();
            connection.close();

        } catch (SQLException | ClassNotFoundException e) {
            System.out.println("Error: " + e.getMessage());
        }
    }
}
content_copyCOPY