Welcome to our guide on establishing a database connection. Below are the steps to connect to a database using various methods.
Connection Methods
Using JDBC
- Download the JDBC driver for your database.
- Set up the connection URL, username, and password.
- Use the
DriverManager.getConnection()
method to establish the connection.
Using Python
- Install the
sqlite3
orpymysql
package. - Use the
sqlite3.connect()
orpymysql.connect()
method to establish the connection.
- Install the
Using Node.js
- Install the
mysql
orpg
package. - Use the
mysql.createConnection()
orpg.connect()
method to establish the connection.
- Install the
Example
Here's a simple example of a database connection using Python and SQLite:
import sqlite3
# Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
# Insert a record
cursor.execute("INSERT INTO users (name, email) VALUES ('John Doe', 'john@example.com')")
# Commit the changes
conn.commit()
# Close the connection
conn.close()
For more information on Python database connections, visit our Python Database Connection Guide.
Image
[
Database Connection Example