14. Write a java program to establish connection to a database and execute simple SQL queries.

PHOTO EMBED

Thu Oct 31 2024 16:17:32 GMT+0000 (Coordinated Universal Time)

Saved by @varuntej #kotlin

java 
Copy code 
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.Statement; 
 
public class DatabaseConnection { 
  public static void main(String[] args) { 
    try { 
      Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/testdb", "user", 
"password"); 
      Statement stmt = con.createStatement(); 
      stmt.executeUpdate("INSERT INTO books (title) VALUES ('Sample Book')"); 
      System.out.println("SQL Query Executed"); 
    } catch (Exception e) { 
      System.out.println(e); 
    } 
  } 
} 
 
Set Up Your Database: 
 
Ensure you have a MySQL server running on localhost with a database named testdb. 
Create a books table with at least a title column: 
sql 
Copy code 
CREATE TABLE books ( 
    id INT AUTO_INCREMENT PRIMARY KEY, 
    title VARCHAR(255) NOT NULL 
); 
 
Compile the java code in cmd and expected output 
SQL Query Executed
[OR]
import java.sql.Connection; 
import java.sql.DriverManager; 
import java.sql.ResultSet; 
import java.sql.Statement; 
 
public class App { 
    public static void main(String[] args) { 
        // Database credentials 
        String url = "jdbc:mysql://localhost:3306/testdb"; 
        String user = "root"; 
        String password = "Varun13@"; 
 
        // SQL query 
        String query = "SELECT * FROM books"; 
 
        // Establish connection and execute query 
        try (Connection conn = DriverManager.getConnection(url, user, password); 
             Statement stmt = conn.createStatement(); 
             ResultSet rs = stmt.executeQuery(query)) { 
 
            System.out.println("Connected to the database!"); 
 
            // Process the result set 
            while (rs.next()) { 
                int id = rs.getInt("id"); 
                String name = rs.getString("name"); 
                System.out.println("ID: " + id + ", Name: " + name); 
            } 
 
        } catch (Exception e) { 
            e.printStackTrace(); 
        } 
    } 
}
Connected to the database!
content_copyCOPY