SQL Connectivity Code Examples
1. Python – MySQL
import [Link]
conn = [Link](
host="localhost",
user="root",
password="password",
database="testdb"
)
if conn.is_connected():
print("Connected to MySQL")
[Link]()
2. Java – MySQL (JDBC)
import [Link];
import [Link];
public class Main {
public static void main(String[] args) {
try {
String url = "jdbc:mysql://localhost:3306/testdb";
String user = "root";
String pass = "password";
Connection con = [Link](url, user, pass);
[Link]("Connected to MySQL");
[Link]();
} catch (Exception e) {
[Link]();
}
}
}
3. PHP – MySQL
<?php
$conn = mysqli_connect("localhost", "root", "password", "testdb");
if (!$conn) {
die("Connection failed");
}
echo "Connected to MySQL";
mysqli_close($conn);
?>
4. C# – SQL Server
using System;
using [Link];
class Program {
static void Main() {
string connStr = "Server=localhost;Database=testdb;Trusted_Connection=True;";
SqlConnection con = new SqlConnection(connStr);
[Link]();
[Link]("Connected to SQL Server");
[Link]();
}
}
5. [Link] – PostgreSQL
const { Client } = require('pg');
const client = new Client({
host: 'localhost',
user: 'postgres',
password: 'password',
database: 'testdb',
port: 5432
});
[Link]()
.then(() => [Link]("Connected to PostgreSQL"))
.catch(err => [Link](err))
.finally(() => [Link]());