Python: Writing Values to Table In MSSQL Server - python

I currently have a connection successfully established with a Database in MSSQL Server.
Below is my code (login credentials removed).
import pypyodbc
connection = pypyodbc.connect('Driver={XXX};'
'Server=XXX;'
'Database=XXX;'
'uid=XXX;'
'pwd=XXX')
cursor = connection.cursor()
Below is what I'm trying to insert into SQL table:
cursor.execute("INSERT INTO MODREPORT(rowid, location) VALUES (?,?)", (3, 'fleet'))
connection.commit
connection.close()
After running the execute code the following appears:
<bound method Connection.commit of <pypyodbc.Connection object at 0x0000000009CB88D0>>
BUT nothing is written into the SQL table

You need to call connection.commit() as a function, not just reference the bound method.
cursor.execute("INSERT INTO MODREPORT(rowid, location) VALUES (?,?)", (3, 'fleet'))
connection.commit()
connection.close()

Related

Inserting values from Python into SQL Server

I want to insert values into a SQL Server table, from Python.
Here is my table in SQL Server:
CREATE TABLE DB.type.[Ref]
(
[Type_Ref] varchar(65),
[ID_match] varchar(65),
[Data] varchar(65)
PRIMARY KEY ([Type_Ref], [ID_match])
)
To insert values from python I wrote this code:
conn = pyodbc.connect('Driver={ODBC Driver 17 for SQL Server};'
'Server=????;'
'Database=DB;'
'Trusted_Connection=yes;')
cursor = conn.cursor()
sql = "INSERT INTO DB.Ref (Type_Ref, ID_match, Data) VALUES (?, ?, ?)"
cursor.execute(sql, (DATA[Type_Ref], DATA[ID_match], DATA[Data]))
conn.commit()
cursor.close()
conn.close()
However, when I run Python, I don't see any rows of data in SQL Server...
I noticed my IDE is giving this, after I run the python code above:
Process finished with exit code -1073741819 (0xC0000005)
Solution: I solved this problem by deleting the table in sql-server and create a new one.
I think you are not building your conn object correctly. When I try to match your pattern, I receive a TypeError. Try this instead:
server='server'
database='database'
user='username'
password='secret'
conn = pyodbc.connect(
server=server,
database=database,
user=username,
password=password,
port=1433,
driver='ODBC Driver 17 for SQL Server'
)
The rest of your code looks like it should work fine.
try the following:
Columns = ['Type_Ref', 'ID_match', 'Data']
sql = "INSERT INTO dbo.Ref([Type_Ref], [ID_match], [Data]) VALUES (?,?,?)"
cursor.executemany(sql, DATA[Columns].values.tolist())
conn.commit()
Thaks for the help, I solved this problem by deleting the table in sql-server and create a new one.

Why I receive error pyodbc.Error: ('HY000', 'The driver did not supply an error!')

I don't understand? Why I receve error: 'HY000', 'The driver did not supply an error!When I insert date time? But when I insert Null all is work. Please help me with it.
My code:
now=now.strftime('%Y-%m-%d %H:%M:%S')
connect = pyodbc.connect("DRIVER={SQL Server};Server=Study;Database=test;Trusted_Connection=yes;", autocommit=False)
cursor=connect.cursor()
cursor.execute("""
use base_for_time insert table_for_time_and_count values (Null,'"""+now+"""',Null,Null,Null)""")
connect.commit()
connect.close()
This might useful.
I think the issue is in your query and in your connection.
update connection:
connect = pyodbc.connect("DRIVER={SQL Server};SERVER=*****;UID=****;PWD=****;TRUSTED_CONNECTION=yes;", autocommit=False)
you're using executing multiple SQL statements in your single execution.
execute your statements one by one or use semicolon(;) instead between two queries.
cursor.execute("use db_name; insert into table_name values (val1,val2,..,valn);")

Print Data from MySQL Database to Console from Python

I'm using Visual Studio 2017 with a Python Console environment. I have a MySQL database set up which I can connect to successfully. I can also Insert data into the DB. Now I'm trying to display/fetch data from it.
I connect fine, and it seems I'm fetching data from my database, but nothing is actually printing to the console. I want to be able to fetch and display data, but nothing is displaying at all.
How do I actually display the data I select?
#importing module Like Namespace in .Net
import pypyodbc
#creating connection Object which will contain SQL Server Connection
connection = pypyodbc.connect('Driver={SQL Server};Server=DESKTOP-NJR6F8V\SQLEXPRESS;Data Source=DESKTOP-NJR6F8V\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False')
cursor = connection.cursor()
SQLCommand = ("SELECT ID FROM MyAI_DB.dbo.WordDefinitions WHERE ID > 117000")
#Processing Query
cursor.execute(SQLCommand)
#Commiting any pending transaction to the database.
connection.commit()
#closing connection
#connection.close()
I figured it out. I failed to include the right Print statement. Which was:
print(cursor.fetchone())
I also had the connection.commit statement in the wrong place (it was inserted even executing the Print statement). The final code that worked was this:
#importing module Like Namespace in .Net
import pypyodbc
#creating connection Object which will contain SQL Server Connection
connection = pypyodbc.connect('Driver={SQL Server};Server=DESKTOP-NJR6F8V\SQLEXPRESS;Data Source=DESKTOP-NJR6F8V\SQLEXPRESS;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False')
cursor = connection.cursor()
SQLCommand = ("SELECT * FROM MyAI_DB.dbo.WordDefinitions")
#Processing Query
cursor.execute(SQLCommand)
#Commiting any pending transaction to the database.
print(cursor.fetchone())
connection.commit()
#closing connection
#connection.close()

Python not inserting data's into mysql

I am testing Python and Mysql in that i am able to create and delete table's but i am unable to insert data in them.I searched stackoverflow and mostly they suggest to use
commit()
So i used it and even after i used the data is not inserted into the database.Please help me.
This is the code i use it creates the table but not inserting data
import MySQLdb
db = MySQLdb.connect("localhost","user","password")
cxn = MySQLdb.connect(db='test')
cursor = cxn.cursor()
cursor.execute("CREATE TABLE users(name VARCHAR(40),id VARCHAR(40))")
cursor.execute("INSERT INTO users(name,id) VALUES('John','1')")
db.commit()
print "Opertion completed successfully"
Are db and cxn connections to the same database?
You should establish your connection using following:
db = MySQLdb.connect(host="localhost",
db="test",
user="user",
passwd="password")
The cursor should then be derived from this connection via:
cursor = db.cursor()
I would hazard that your issue is coming from the ambiguity between db and cxn.

How can I create a database using pymssql

Im trying to create a database using pymssql and im getting this error.
cur.execute("CREATE DATABASE %s;" % self.getsql('dbname'), conn)
gives
*** OperationalError: (226, 'CREATE DATABASE statement not allowed within multi-
statement transaction.DB-Lib error message 226, severity 16:\\nGeneral SQL Serve
r error: Check messages from the SQL Server\\n')
What does this mean ??
The issue was that cur.execute starts a transaction every time, but 'CREATE DATABASE' operation cannot be excuted within a transaction
http://social.msdn.microsoft.com/Forums/pl/adodotnetdataproviders/thread/594ff024-8af6-40b3-89e0-53edb3ad7245
>>> connection.autocommit(True)
>>> cursor = connection.cursor()
>>> cursor.execute("CREATE DATABASE Foo")
>>> connection.autocommit(False)
This to works. Strangely its not documented in pymssql ... hmmm

Categories