I`m just started to learn SQLite. I use python.
The question is how to create rows in tables, so that they are uniqe by name and how to use (extract) id1 and id2 to insert them into a separate table.
import sqlite3
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
id1 integer primary key autoincrement, name)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
id2 integer primary key autoincrement, name)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT INTO table2 VALUES (null, "The Invention of Wings")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
c.execute('INSERT INTO table1 VALUES (null, "Colleen Hoover")')
c.execute('INSERT INTO table2 VALUES (null, "Maybe Someday")')
#c.execute('INSERT INTO t1_t2 VALUES (id1, id2)')
Thanks.
I think you have some problems with the table creation. I doubt that it worked, because the name columns don't have a type. They should probably be varchar of some length. The JOIN table definition isn't right, either.
CREATE TABLE IF NOT EXISTS table1 (
id1 integer primary key autoincrement,
name varchar(80)
);
CREATE TABLE IF NOT EXISTS table2 (
id2 integer primary key autoincrement,
name varchar(80)
);
CREATE TABLE IF NOT EXISTS t1_t2 (
id1 integer,
id2 integer,
primary key(id1, id2),
foreign key(id1) references table1(id1),
foreign key(id2) references table2(id2)
);
I would not create the tables in code. Script them, execute in the SQLite admin, and have the tables ready to go when your Python app runs.
I would think much harder about your table names if these are more than examples.
I found the problem of unique names on unique column problem.
Actually, I should change INSERT to INSERT OR IGNORE
import sqlite3
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('''CREATE TABLE IF NOT EXISTS table1(
id1 integer primary key autoincrement, name TEXT unique)''')
c.execute('''CREATE TABLE IF NOT EXISTS table2(
id2 integer primary key autoincrement, name TEXT unique)''')
c.execute('CREATE TABLE IF NOT EXISTS t1_t2(id1, id2)') # many-to-many
conn.commit()
conn.close()
conn = sqlite3.connect('my.db')
c = conn.cursor()
c.execute('INSERT OR IGNORE INTO table1 VALUES (null, "Sue Monk Kidd")')
c.execute('INSERT OR IGNORE INTO table2 VALUES (null, "The Invention of Wings")')
Related
I have created a function that is supposed to send all the items, with a stock level of less than 10, in my database to a text file. But i am not receiving any data when I press the reorder button.
def Database():
global conn, cursor
conn = sqlite3.connect("main_storage.db")
cursor = conn.cursor()
cursor.execute("CREATE TABLE IF NOT EXISTS `admin` (admin_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, username TEXT, password TEXT)")
cursor.execute("CREATE TABLE IF NOT EXISTS `product` (product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, product_name TEXT, product_qty TEXT, product_price TEXT)")
cursor.execute("CREATE TABLE IF NOT EXISTS `basket` (product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL, product_name TEXT, product_qty TEXT, product_price TEXT)")
cursor.execute("SELECT * FROM `admin` WHERE `username` = 'admin' AND `password` = 'admin'")
if cursor.fetchone() is None:
cursor.execute("INSERT INTO `admin` (username, password) VALUES('admin', 'admin')")
conn.commit()
def reorder():
global items
Database()
cursor.execute("SELECT `product_name` FROM `product` WHERE `product_qty` <= 10")
items = cursor.fetchall()
print(items)
cursor.close()
conn.close()
I expect the output to be an array of items within my database e.g. [44, 'motherboard', 9, 80] where 44 is product_id, motherboard is product_name, 9 is product_stock and 80 is product_price. I am actually getting an array with nothing in like: []
product_qty is defined as a TEXT column, so comparisons like <= will be performed between the string values of operands. This may not give the results that you expect:
>>> '8' < '10'
False
Recreate your tables with INTEGER or REAL as the column type for numeric values to get the behaviour that you want. For example:
cursor.execute("""CREATE TABLE IF NOT EXISTS `product` """
"""(product_id INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,"""
"""product_name TEXT, product_qty INTEGER, product_price REAL)""")
I am running a server through Apache using Python 3.4 as a cgi and a MySQL database server on Windows 10. When I try to run my function for creating the database I get the error:
DatabaseError: 1005 (HY000): Can't create table `testdb`.`studentexam` (errno: 150
"Foreign key constraint is incorrectly formed")
The function for creating the database
import mysql.connector as conn
#connect to server
db=conn.connect(host="localhost",user="root",password="")
cursor=db.cursor()
#create database
cursor.execute("""CREATE DATABASE IF NOT EXISTS Testdb""")
db.commit()
#use database
cursor.execute("""USE Testdb""")
db.commit()
#create Teacher table
cursor.execute("""CREATE TABLE IF NOT EXISTS Teacher(
TeacherUsername VARCHAR(255) PRIMARY KEY,
TeacherPassword TEXT)""")
db.commit()
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentNo INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create exam table
cursor.execute("""CREATE TABLE IF NOT EXISTS Exam(
TestName VARCHAR(255) PRIMARY KEY,
TestTotalMarks TEXT,
Teacher VARCHAR(255),
FOREIGN KEY(Teacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create StudentExam table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentExam(
TestName VARCHAR(255),
StudentID INT,
StudentTotalMarks INT,
PRIMARY KEY(TestName,StudentID),
FOREIGN KEY(TestName) REFERENCES Exam(TestName),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create ExamSection table
cursor.execute("""CREATE TABLE IF NOT EXISTS ExamSection(
TestName VARCHAR(255),
SectionID INT,
PRIMARY KEY(TestName,SectionID),
FOREIGN KEY(TestName) REFERENCES Exam(TestName),
FOREIGN KEY(SectionID) REFERENCES Section(SectionID))""")
db.commit()
#create Section table
cursor.execute("""CREATE TABLE IF NOT EXISTS Section(
SectionID INT PRIMARY KEY,
SectionName TEXT,
SectionTotalMarks INT)""")
db.commit()
#create Question table
cursor.execute("""CREATE TABLE IF NOT EXISTS Question(
QuestionID INT PRIMARY KEY,
SectionID VARCHAR(255),
Image TEXT,
Question TEXT,
PossibleAnswer TEXT,
CorrectAnswer TEXT,
QuestionType TEXT,
FOREIGN KEY(SectionID) REFERENCES Section(SectionID))""")
db.commit()
#create QuestionResults Table
cursor.execute("""CREATE TABLE IF NOT EXISTS QuestionResults(
QuestionID INT,
StudentID INT,
SectionID VARCHAR(255),
StudentAnswer TEXT,
PRIMARY KEY(QuestionID,StudentID),
FOREIGN KEY(QuestionID) REFERENCES Question(QuestionID)
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create Revision table
cursor.execute("""CREATE TABLE IF NOT EXISTS Revision(
RevisionID INT PRIMARY KEY,
RevisionSheet TEXT,
TeacherUsername VARCHAR(255),
FOREIGN KEY(TeacherUsername) REFERENCES Teacher(TeacherUsername))""")
db.commit()
#create StudentRevition table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentRevision(
RevisionID INT,
StudentID INT,
PRIMARY KEY(RevisionID,StudentID),
FOREIGN KEY(RevisionID) REFERENCES Revision(RevisionID),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
#create StudentResults table
cursor.execute("""CREATE TABLE IF NOT EXISTS StudentResults(
SectionID VARCHAR(255),
StudentID INT,
StudentSectionMarks INT,
PRIMARY KEY(SectionID,StudentID),
FOREIGN KEY(SectionID) REFERENCES Section(SectionID),
FOREIGN KEY(StudentID) REFERENCES Student(StudentID))""")
db.commit()
cursor.close()
EDIT: I Changed StudentNo to StudentID and now get the error:
DatabaseError: 1005 (HY000): Can't create table `testdb`.`examsection` (errno: 150
"Foreign key constraint is incorrectly formed")
Change this:
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentNo INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
to this:
#create student table
cursor.execute("""CREATE TABLE IF NOT EXISTS Student(
StudentID INT PRIMARY KEY,
StudentSurname TEXT,
StudentForename TEXT,
StudentTeacher VARCHAR(255),
StudentPassword TEXT,
FOREIGN KEY(StudentTeacher) REFERENCES Teacher(TeacherUsername))""")
db.commit()
When creating StudentExam, you are referencing Student.StudentId which doesn't exist. It looks like you rather want to reference Student.StudentNo.
edit:
When you create ExamSection, you reference the Section table, which doesn't exist yet. Move the Section creation state up so that it runs and commits before you create ExamSection.
A database is composed of 4 tables: Table1, table2, table3 and table4.
For a given query Q. If Q = Name_1. I want to select all the fields in tables 1, 2, 3 and 4 and save them in an array using python.
create Tables:
Create Table table1 (ID1 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100));
Create table table2 (ID2 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T1 INT, Foreign Key(ID_T1) references table1(ID1));
Create table table3 (ID3 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T1 INT, Foreign Key(ID_T1) references table1(ID1));
Create table table4 (ID4 INT PRIMARY KEY NOT NULL, NAME VARCHAR(100),ID_T2 INT, Foreign Key(ID_T2) references table2(ID2));
Insert Data in tables:
insert into table1 (ID1,NAME) values ("1", "john");
insert into table2 (ID2,NAME,ID_T1) values ("1", "math","1");
insert into table3 (ID3,NAME,ID_T1) values ("1", "physics","1");
insert into table4 (ID4,NAME,ID_T2) values ("1", "friend of","1");
Here is the query:
SELECT * FROM Table1 AS t1
JOIN table3 as t3 ON t1.ID_table1 = t3.ID_table1
JOIN table2 as t2 ON t1.ID_table1 = t2.ID_table1
JOIN table4 as t4 ON t2.ID_table2 = t4.ID_table2
I am trying to INSERT or REPLACE INTO t1 if the name is already there. I understand if the id is set then replace will work, but I need it to react to name.
import sqlite3
def insert(name):
cur.execute('INSERT OR REPLACE INTO t1(name) VALUES(?)', [name])
def select():
return cur.execute('SELECT * FROM t1').fetchall()
conn = sqlite3.connect('test')
cur = conn.cursor()
cur.execute('DROP TABLE IF EXISTS t1')
cur.execute('''CREATE TABLE IF NOT EXISTS t1(
id INTEGER PRIMARY KEY,
name TEXT NOT NULL
)''')
insert('jack')
insert('jack')
insert('jack')
print select()
output
[(1, u'jack'), (2, u'jack'), (3, u'jack')]
INSERT or REPLACE ... will do replace only if there are collisions. And as your name column isnt collidable, this event cannot accur (at least not on name). You need to make name collidable:
CREATE UNIQUE INDEX IF NOT EXISTS iname ON t1 (name)
Also note that you dont need to have id column, because sqlite3 has ROWID on every table.
I want to insert data in MYSQL database using python
here my code
import MySQLdb
#connect to db
db= MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="new_schema")
#setup cursor
cursor = db.cursor()
#create anooog1 table
cursor.execute("DROP TABLE IF EXISTS try")
sql = """CREATE TABLE try (
COL1 INT, COL2 INT )"""
cursor.execute(sql)
#insert to table
cursor.execute("""INSERT INTO try VALUES (%s,%s)""",(188,90))
db.commit()
db.rollback()
#show table
cursor.execute("""SELECT * FROM try""")
print cursor.fetchall()
db.close()
but the error is in my sql
Error: `new_schema`.`try`: table data is not editable because there is no primary key defined for the table ...
What shall I do?
Your error is because you've created a table with no primary key.
Use this statement (or similar):
sql = """CREATE TABLE try (COL1 INT, COL2 INT, PRIMARY KEY (COL1))"""
Here we specify that COL1 is to be the primary key for the table. Modify as you need to suit your requirements.
If you wanted to add a string column (with length 128) to your table:
CREATE TABLE try (COL1 INT, COL2 INT, MyString VARCHAR(128), PRIMARY KEY (COL1))