xxxxxxxxxx
# Importing the necessary library
import sqlite3
# Connecting to a SQLite database (replace 'example.db' with the path to your database file)
conn = sqlite3.connect('example.db')
# Creating a cursor object to execute queries
cursor = conn.cursor()
# Example: Creating a table in the database
create_table_query = '''
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY,
name TEXT NOT NULL,
age INTEGER
);
'''
cursor.execute(create_table_query)
# Example: Inserting data into the table
user_data = (1, 'John Doe', 25)
insert_query = 'INSERT INTO users (id, name, age) VALUES (?, ?, ?)'
cursor.execute(insert_query, user_data)
# Example: Fetching data from the table
select_query = 'SELECT * FROM users'
cursor.execute(select_query)
rows = cursor.fetchall()
for row in rows:
print(row)
# Committing the changes and closing the connection
conn.commit()
conn.close()
xxxxxxxxxx
# Here is a sample from https://www.w3schools.com/python/python_mysql_create_db.asp
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
xxxxxxxxxx
#connect to sqlite database in python
import sqlite3
connection = sqlite3.connect("survey.db")
cursor = connection.cursor()
cursor.execute("SELECT Site.lat, Site.long FROM Site;")
results = cursor.fetchall()
for r in results:
print(r)
cursor.close()
connection.close()
xxxxxxxxxx
#create database in python with mysql
import mysql.connector
mydb = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword"
)
mycursor = mydb.cursor()
mycursor.execute("CREATE DATABASE mydatabase")
xxxxxxxxxx
# Install MySQL on system, run 'pip install mysql.connector', import in script
import mysql.connector
# Make connection to database
database=mysql.connector.connect(host="localhost", user="root", passwd="<your_password>")
cursor = database.cursor()
# to create database
cursor.execute("create database harshdb")
xxxxxxxxxx
use a python library called pyodbc
pip install pyodbc, you will also need to download the relavant SQL driver for the type and version of what SQL you are using.