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!
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter