I'm trying to create a table on a tempdb database on a local server KHBW001 using MSSQL. My code is:
import pyodbc
connection = pyodbc.connect('Driver={SQL Server};'
'Server=KHBW001;'
'Database=tempdb;'
'Trusted_Connection=yes;')
cursor = connection.cursor()
cursor.executemany(
"CREATE TABLE tempdb.dbo.NewTestPyTable(Symbol varchar(15), Shares integer, Price double)") # creates new table
cursor.executemany("""
INSERT INTO tempdb.dbo.NewTestPyTable (Symbol, Shares, Price)
VALUES
[('ETH',55,199.55),
('KHC',66,33.5)]
""") # insert two records into new table
connection.commit()
I'm getting the error:
"CREATE TABLE tempdb.dbo.NewTestPyTable(Symbol varchar(15), Shares
integer, Price double)") # creates new table
TypeError: function takes exactly 2 arguments (1 given)
I don't quite understand what I'm doing wrong. Please assist
Figured it out...
import pyodbc
connection = pyodbc.connect('Driver={SQL Server};'
'Server=KHBW001;'
'Database=tempdb;'
'Trusted_Connection=yes;')
cursor = connection.cursor()
cursor.execute(
"CREATE TABLE NewTestPyTable(Symbol varchar(15), Shares integer, Price integer)") # creates new table
params = [('ETH', 55, 199),
('KHC', 66, 33)]
# insert two records into new table
cursor.executemany(
"INSERT INTO tempdb.dbo.NewTestPyTable (Symbol, Shares, Price) VALUES (?, ?, ?)", params)
connection.commit()
i think first of all the problem is in table creation
here is the documentation how to create it correctly
https://www.w3schools.com/sql/sql_create_table.asp
type of data in SQL
https://www.journaldev.com/16774/sql-data-types
further it seems to me
you also need to use the money type for the price.
that's how i would do:
import pyodbc
connection = pyodbc.connect('Driver={SQL Server};'
'Server=KHBW001;'
'Database=tempdb;'
'Trusted_Connection=yes;')
cursor = connection.cursor()
cursor.executemany(
"CREATE TABLE tempdb.dbo.NewTestPyTable(Symbol varchar(15), Shares int, Price money)") # creates new table
cursor.executemany("""
INSERT INTO tempdb.dbo.NewTestPyTable (Symbol, Shares, Price)
VALUES
('ETH',55,199.55),
('KHC',66,33.5);
""") # insert two records into new table
connection.commit()
Related
I have this error with one of my sqlite database tables that I cannot solve, even after looking online for hours. I have also tried deleting the database and starting with a new one but this did not work.
The Error: line 90, in submit1
c.execute("INSERT INTO responses VALUES (:company, :roles, :interview, :offer, :wage_offered, :start_date)",
sqlite3.OperationalError: table responses has 5 columns but 6 values were supplied
However there are 6 columns so I do not understand why this error is cropping up.
the submit1 function Code is posted below:
#create submit function for
def submit1():
# Create a databse or connect to one
connection = sqlite3.connect('jobtracker.db')
#Create a cursor
c = connection.cursor()
# Insert into table
c.execute("INSERT INTO responses VALUES (:company, :roles, :interview, :offer, :wage_offered, :start_date)",
{
'company': company1.get(),
'roles': role1.get(),
'interview': interview.get(),
'offer': offer.get(),
'wage_offered': wage_offered.get(),
'start_date': start_date.get()
})
# Commit changes
connection.commit()
# Close connection
connection.close()
And here is the code for the database:
#Creating database
conn = sqlite3.connect('jobtracker.db')
c = conn.cursor()
#Creating tables for database
c.execute("""CREATE TABLE IF NOT EXISTS applications (
company text,
role text,
industry text,
location text,
wage_min integer,
wage_max integer,
start_date integer,
status text
)""")
c.execute("""CREATE TABLE IF NOT EXISTS responses (
company text,
role text,
interview integer,
offer integer
wage_offered integer,
start_date integer
)""")
conn.commit()
conn.close()
#create submit function for
def submit():
# Create a databse or connect to one
connection = sqlite3.connect('jobtracker.db')
#Create a cursor
c = connection.cursor()
# Insert into table
c.execute("INSERT INTO applications VALUES (:company, :roles, :industry, :location, :wage_min, :wage_max, :start_date, :status)",
{
'company': company.get(),
'roles': role.get(),
'industry': industry.get(),
'location': location.get(),
'wage_min': wage_min.get(),
'wage_max': wage_max.get(),
'start_date': start_date.get(),
'status': status.get()
})
# Commit changes
connection.commit()
# Close connection
connection.close()
Thank you in advance.
I think the table has only 5 fields
You are trying to insert 6 fields
I am trying to get the ID of a newly inserted row by using OUTPUT. However, I encountered the HY010 error. The following query/code is what I use:
string = """
SET NOCOUNT ON;
DECLARE #NEWID TABLE(ID INT);
INSERT INTO dbo.t1 (Username, Age)
OUTPUT inserted.id INTO #NEWID(ID)
VALUES(?, ?)
SELECT ID FROM #NEWID
"""
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
the last line id = cursor.fetchone()[0] led to a HY010 error (see below). Any advice would be greatly appreciated!
pyodbc.Error: ('HY010', '[HY010] [Microsoft][ODBC SQL Server Driver]Function sequence error (0) (SQLFetch)')
I was able to reproduce your issue, and I was able to avoid it by retrieving the id value immediately after the INSERT and before the commit. That is, instead of
cursor.execute(string, "John Doe", 35)
cursor.commit()
id = cursor.fetchone()[0]
I did
cursor.execute(string, "John Doe", 35)
id = cursor.fetchone()[0] # although cursor.fetchval() would be preferred
cursor.commit()
For me only this worked with Azure SQL Serverless (using pyodbc==4.0.28):
cursor.execute(insert_statement, param_value_list)
cursor.execute("SELECT ##IDENTITY AS ID;")
return cursor.fetchone()[0]
If you're using SQLAlchemy with an engine, then you can retrieve the PyODBC cursor like this before running the query and fetching the table ID.
connection = sql_alchemy_engine.raw_connection()
cursor = connection.cursor()
result = cursor.execute(
"""
INSERT INTO MySchema.MyTable (Col1, Col2) OUTPUT INSERTED.MyTableId
VALUES (?, ?);
""",
col1_value,
col2_value,
)
myTableId = cursor.fetchone()[0]
cursor.commit()
print("my ID is:", myTableId)
I have a Python string (or potentially a Python dictionary) that I'd like to insert to MySql table.
My String is the following:
{'ticker': 'BTC', 'avail_supply': 16479075.0, 'prices': 2750.99, 'name': 'Bitcoin', '24hvol': 678995000.0}
I have the same kind of error if I want to insert the Dict format.
I really don't understand this kind of error (i.e. the '\' in-between the components of the string).
How can I deal with this error? Any why to properly insert a whole string to a particular TEXT cell in SQL?
Many thanks !!
Here is how to connect, make a table, and insert in the table.
import MySQLdb as mdb
import sys
#connect
con = mdb.connect('localhost', 'testuser', 'test623', 'testdb');
with con:
#need the cursor object so you can pass sql commands, also there is a dictionary cursor
cur = con.cursor()
#create example table
cur.execute("CREATE TABLE IF NOT EXISTS \
Writers(Id INT PRIMARY KEY AUTO_INCREMENT, Name VARCHAR(25))")
#insert what you want
cur.execute("INSERT INTO Writers(Name) VALUES('Jack London')")
cur.execute("INSERT INTO Writers(Name) VALUES('Honore de Balzac')")
cur.execute("INSERT INTO Writers(Name) VALUES('Lion Feuchtwanger')")
cur.execute("INSERT INTO Writers(Name) VALUES('Emile Zola')")
cur.execute("INSERT INTO Writers(Name) VALUES('Truman Capote')")
Example above will make a table with 2 cols, one ID and one name
look here on an example on how to insert stuff from dictionary with keys and list as value to sql, basically you need place holders
sql = "INSERT INTO mytable (a,b,c) VALUES (%(qwe)s, %(asd)s, %(zxc)s);"
data = {'qwe':1, 'asd':2, 'zxc':None}
conn = MySQLdb.connect(**params)
cursor = conn.cursor()
cursor.execute(sql, data)
cursor.close()
conn.close()
or you can go with this as an example for a simple straight forward dict
placeholders = ', '.join(['%s'] * len(myDict))
columns = ', '.join(myDict.keys())
sql = "INSERT INTO %s ( %s ) VALUES ( %s )" % (table, columns, placeholders)
cursor.execute(sql, myDict.values())
I have a MySQL Table named TBLTEST with two columns ID and qSQL. Each qSQL has SQL queries in it.
I have another table FACTRESTTBL.
There are 10 rows in the table TBLTEST.
For example, On TBLTEST lets take id =4 and qSQL ="select id, city, state from ABC".
How can I insert into the FACTRESTTBL from TBLTEST using python, may be using dictionary?
Thx!
You can use MySQLdb for Python.
Sample code (you'll need to debug it as I have no way of running it here):
#!/usr/bin/python
import MySQLdb
# Open database connection
db = MySQLdb.connect("localhost","testuser","test123","TESTDB" )
# prepare a cursor object using cursor() method
cursor = db.cursor()
# Select qSQL with id=4.
cursor.execute("SELECT qSQL FROM TBLTEST WHERE id = 4")
# Fetch a single row using fetchone() method.
results = cursor.fetchone()
qSQL = results[0]
cursor.execute(qSQL)
# Fetch all the rows in a list of lists.
qSQLresults = cursor.fetchall()
for row in qSQLresults:
id = row[0]
city = row[1]
#SQL query to INSERT a record into the table FACTRESTTBL.
cursor.execute('''INSERT into FACTRESTTBL (id, city)
values (%s, %s)''',
(id, city))
# Commit your changes in the database
db.commit()
# disconnect from server
db.close()
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))