Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Database Connection

Data base connection

Uploaded by

arafaths062
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Database Connection

Data base connection

Uploaded by

arafaths062
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 1

import java.sql.

Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DatabaseConnection {


public static void main(String[] args) {
// Database connection parameters
String url = "jdbc:mysql://localhost:3306/ani"; // Update the database URL
if necessary
String user = "Arafath"; // Update with your MySQL username
String password = "sacet123"; // Update with your MySQL password

try {
// 1. Load the JDBC driver
Class.forName("com.mysql.cj.jdbc.Driver");

// 2. Establish the connection


Connection conn = DriverManager.getConnection(url, user, password);

// 3. Check if the connection is successful


if (conn != null) {
System.out.println("Connected to the database successfully!");

// SQL statement to insert a new student


String sql = "INSERT INTO students (id, name, course) VALUES (?, ?,
?)";
PreparedStatement stmt = conn.prepareStatement(sql);

// Set the values for the new student record


stmt.setInt(1, 2); // Set the ID (change as needed)
stmt.setString(2, "Vijay"); // Set the name
stmt.setString(3, "AIML"); // Set the course

// Execute the insert operation


int rowsAffected = stmt.executeUpdate();
if (rowsAffected > 0) {
System.out.println("Data inserted successfully!");
} else {
System.out.println("Data insertion failed.");
}

// Close the PreparedStatement


stmt.close();
}

// 4. Close the connection


conn.close();
} catch (ClassNotFoundException e) {
System.out.println("JDBC Driver not found.");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("Database connection failed.");
e.printStackTrace();
}
}
}

You might also like