0

Using python 2.7.5, I've written the following code down to compile based off of an online course I'm taking that shows how sqlite3 works with python

import sqlite3 as sql

database1 = sql.connect('test1.db')

db1_cursor = database1.cursor()

cmd = 'CREATE TABLE IF NOT EXISTS users(username TEXT,password TEXT)'

cmd2 = 'INSERT INTO users(username,password) VALUES("testuser,testpassword")'

cmd3 = 'SELECT username,password FROM users'

db1_cursor.execute(cmd)

db1_cursor.execute(cmd2)

db1_cursor.execute(cmd3)

database1.commit()

for x in db1_cursor:

    print(x)

Now, upon running this code it gives me the following operation error:

Traceback (most recent call last):

File "C:\Users\Ryan\My Code Projects\Learning\udemycourse.py", line 11, in <module>

db1_cursor.execute(cmd2)

OperationalError: 1 values for 2 columns

Why does it give this error for db1_cursor.execute(cmd2) but not for db1_cursor.execute(cmd1) and how can I fix this?

2 Answers 2

3

I think you meant

Values ("testuser","testpassword")
Sign up to request clarification or add additional context in comments.

Comments

0

A better way of doing the insert would be cmd2 = 'INSERT INTO users(username,password) VALUES(?, ?)'

Creating placeholders

db1_cursor.execute(cmd2, ('testuser','testpassword'))

and passing the values as a tuple

1 Comment

This works but I decided to use the answer above since it doesn't change too much of the syntax of the code following along with my udemy course. Although, in the course it prints out (u'testuser', u'testpassword') twice as opposed to what the course shows where it only prints out in the console once. Why is this?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.