I want to insert some maximo data into table in another database server. I create an automation script like this
from psdi.security import UserInfo
from psdi.server import MXServer
from psdi.util import MXApplicationException
from psdi.util import MXException
from java.rmi import RemoteException
from java.lang import System
from java.text import Format, DateFormat, SimpleDateFormat
from java.lang import System
mx = MXServer.getMXServer();
ui = mx.getSystemUserInfo();
url= "jdbc:sqlserver://MAXIMODEMO:1433; database=IntegrationTest; user=maxadmin; password=password; encrypt=false; trustServerCertificate=false; loginTimeout=30;";
from java.lang import Class
from java.sql import DriverManager,SQLException
#load driver and register
Class.forName(jdbc_driver).newInstance()
DriverManager.registerDriver(Class.forName(jdbc_driver).newInstance())
#get Connection
#connection = DriverManager.getConnection(jdbc_url, jdbc_user), jdbc_password)
connection = DriverManager.getConnection(url)
#find if item exist
sql = "Select itemnum from item where itemnum='"+mbo.getString("ITEMNUM")+"'"
result = connection.createStatement().executeQuery(sql)
sqlinsert = ""
sdf = SimpleDateFormat("yyyy-MM--dd");
if(result.next()) :
sqlinsert = "Update Item set description='"+mbo.getString("DESCRIPTION")+"', orderunit='"+mbo.getString("ORDERUNIT")+"', status='"+mbo.getString("STATUS")+"' where ItemNum='"+mbo.getString("ITEMNUM")+"'"
else:
sqlInsert="Insert into item(itemnum, description, orderunit, statusdate, status, groupname) values('" + mbo.getString("ITEMNUM")+ "','" + mbo.getString("Description") + "', '" + mbo.getString("ORDERUNIT") + "','" + sdf.format(mbo.getDate("STATUSDATE")) + "', '" + mbo.getString("STATUS") + "','" + mbo.getString("GROUPNAME") + "') "
result.close()
result = connection.createStatement().executeQuery(sqlinsert)
connection.close()
There's no error but the data not inserted. the query for select is working fine, it can return the value, but the insert / update is not working.
Did I miss something in executing insert/update query?
You are missing a connection.commit() before your connection.close().
Also, you should be calling executeUpdate() with your insert or update statement text instead of calling executeQuery() with it. The JavaDocs for java.sql.Statement.executeUpdate() say, "Executes the given SQL statement, which may be an INSERT, UPDATE, or DELETE statement or an SQL statement that returns nothing, such as an SQL DDL statement."
Related
I am trying to create(using spring native query) the findAllId for the reactive repository spring data cosmo DB.
Since for the ReactiveCosmosRepository is not implemented.
#Query(value = " SELECT *\n" +
" FROM container_name km\n" +
" WHERE km.id IN (#ids) \n" +
" ORDER BY km.createdDate DESC ")
Flux<ContainerData> findAllById(#Param("ids") String[] ids);
or even
#Query(value = " SELECT *\n" +
" FROM container_name km\n" +
" WHERE km.id IN (#ids) \n" +
" ORDER BY km.createdDate DESC ")
Flux<ContainerData> findAllById(#Param("ids") Iterable<String> ids);
but it is not retrieving any results, and it is not throwing any exception either.
So the question is, how to use IN operator with spring data native query in cosmos db and collection or array out of the box without having to do a workaround.
You should use array_contains
#Query(value = " SELECT *\n" +
" FROM container_name km\n" +
" WHERE array_contains(#ids, km.id, true) \n" +
" ORDER BY km.createdDate DESC ")
Flux<ContainerData> findAllById(#Param("ids") Iterable<String> ids);
conn = pyodbc.connect("DRIVER={SQL Server};"
"SERVER="+server+";"
"UID="+username+";"
"PWD="+password,
autocommit=True)
cursor = conn.cursor()
database= "abcd"
sql_create = (
"DECLARE #sql AS NVARCHAR(MAX);"
"SET #sql = 'if not exists(select * from sys.databases where name = ' + QUOTENAME(?) + ')' + ' CREATE DATABASE ' + QUOTENAME(?);"
"EXEC sp_executesql #sql")
cursor.execute(sql_create,database,database)
Getting error msg like pyodbc.ProgrammingError: ('42S22', u"[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'abcd'. (207) (SQLExecDirectW)")"
Don't use QUOTENAME and concatenation for the WHERE clause parameter. Also, avoid using the legacy SQL Server ODBC driver that ships with Windows to access Azure SQL Database. Instead, download and use a newer ODBC driver. Below is an example with these changes.
conn = pyodbc.connect("DRIVER={ODBC Driver 17 for SQL Server};"
"SERVER="+server+";"
"UID="+username+";"
"PWD="+password,
autocommit=True)
cursor = conn.cursor()
database= "abcd"
sql_create = (
"DECLARE #sql AS NVARCHAR(MAX);"
"SET #sql = N'if not exists(select * from sys.databases where name = #DatabaseName)' + N' CREATE DATABASE ' + QUOTENAME(?) + N';';"
"EXEC sp_executesql #sql, N'#DatabaseName sysname', #DatabaseName = ?;")
cursor.execute(sql_create,database,database)
You could also declare a T-SQL variable for the database name and assign it to the parameter value so that you only need to pass a single parameter:
sql_create = (
"DECLARE #sql AS NVARCHAR(MAX);"
"DECLARE #DatabaseName sysname = ?;"
"SET #sql = N'if not exists(select * from sys.databases where name = #DatabaseName)' + N' CREATE DATABASE ' + QUOTENAME(#DatabaseName) + N';';"
"EXEC sp_executesql #sql, N'#DatabaseName sysname', #DatabaseName = #DatabaseName;")
cursor.execute(sql_create,database)
when trying to insert a row into a table in MS SQL using Python pandas, I got the error " 'nonetype' object is not iterable" when trying to execute the INSERT query in python.I use Python 3.6 and microsoft sql server management studio 2008
my code:
import pyodbc
import pandas as pd
server = 'ACER'
db = 'fin'
# Create the connection
conn = pyodbc.connect('DRIVER={SQL Server};SERVER=' + server + ';DATABASE=' + db + ';Trusted_Connection=yes')
# query db
sql = """INSERT INTO [fin].[dbo].[items] (itemdate, itemtype, name, amount) VALUES('2017-04-01','income','bonus',350) """
#df = pd.read_sql(sql, conn)
df = pd.read_sql(sql, conn)
print(df.to_string())
Somebody suggested using SET NOCOUNT ON, so I tried to modify the query to:
sql = """ SET NOCOUNT ON
---
INSERT INTO [fin].[dbo].[items] (itemdate, itemtype, name, amount) VALUES('2017-04-01','income','bonus',350) """.split("---")
but the execution failed.
What am I doing wrong here? It run's without error, it has created table, but rows are empty. Why?
import sqlite3
sqlite_file = (r"C:\Users\Dragan\PycharmProjects\MyProject\ArchLib2.db")
conn = sqlite3.connect(sqlite_file)
cursor = conn.cursor()
table_name = 'Archive'
sql = 'CREATE TABLE IF NOT EXISTS ' + table_name + '("first_name" varchar NOT NULL, "second_name" varchar NOT NULL)'
cursor.execute(sql)
sql = 'INSERT INTO ' + table_name + '(first_name,second_name) VALUES ("value1","value2");'
cursor.execute(sql)
cursor.close()
Ok so I found why it didn't INSERT data into table.
data in sql = string didnt have good formating ( this ' must be replaced with this "
second if you have string value like "value1" it has to have backslash on both sides like this "\value1\"
third and most important after insert execution line you have to add this line conn.commit()
Final code looks like this:
import sqlite3
sqlite_file = (r"C:\Users\Dragan\PycharmProjects\MyProject\ArchLib2.db")
conn = sqlite3.connect(sqlite_file)
cursor = conn.cursor()
table_name = 'Archive'
sql = "CREATE TABLE IF NOT EXISTS " + table_name + "(first_name varchar NOT NULL, datetime)"
cursor.execute(sql)
sql = "INSERT INTO " + table_name + "(first_name,datetime) VALUES (\"value1\",CURRENT_TIMESTAMP)"
cursor.execute(sql)
conn.commit()
cursor.close()
I have two tables, one in ms sql and other one in sqlite3
I need to update a field in mssql table to the related value from sqlite3 table.
here is my code:
import pypyodbc
import sqlite3
connection = pypyodbc.connect('Driver={SQL Server};'
'Server=****'
'Database=****;'
'uid=****;pwd=****')
cursor = connection.cursor()
SQLCommand = ("select ObjectId, ObjectColumnName,Label from LocalizedLabel "
"where LanguageId = 1065")
sqlUpdate = ("UPDATE LocalizedLabel "
"SET Label = ? "
"WHERE ObjectId = ? and ObjectColumnName = ? and LanguageId = 1065")
cursor.execute(SQLCommand)
results = cursor.fetchall()
srcDB = sqlite3.connect('crmLLDB')
for result in results:
val = (result[0], result[1])
print('SELECT "1065" FROM crm '
'WHERE UPPER(ObjectID)= UPPER(%s) AND ObjectColumnName = %s' % val)
srcCursor = srcDB.execute('SELECT "1065" FROM crm '
'WHERE UPPER(ObjectID)= UPPER(?) AND ObjectColumnName = ?', val)
if srcCursor.fetchone() is None:
print("No translation found for " + result[2])
else:
translation = srcCursor.fetchone()[0]
updateVals = (translation, result[0], result[1])
cursor.execute(sqlUpdate, updateVals)
connection.close()
srcDB.close()
objectId is a GuID and other fields are all strings
the print function returns:
SELECT "1065" FROM crm WHERE UPPER(ObjectID)= UPPER(b'0340B506-2341-DB11-898A-0007E9E17EBD') AND ObjectColumnName = DisplayName
while the watcher gives:
result[0] = 'b\\'0340B506-2341-DB11-898A-0007E9E17EBD\\''
result[1] = 'DisplayName'
this query of course returns this error:
[1] [SQLITE_ERROR] SQL error or missing database (near "'0340B506-2341-DB11-898A-0007E9E17EBD'": syntax error)
while this query :
SELECT "1065" FROM crm WHERE UPPER(ObjectID)= UPPER('0340B506-2341-DB11-898A-0007E9E17EBD') AND ObjectColumnName = 'DisplayName'
return the perfect answer,
can someone point out my problem, please?
appearaently the problem was with pypyodbc and its problem with GuId,
I used pyodbc and everything works fine now!
my final code, if some googler in the future passes by:
import pyodbc
import sqlite3
startTme = datetime.now()
connection = pyodbc.connect('Driver={SQL Server};'
'Server=*****;'
'Database=****;'
'uid=sa;pwd=*****')
cursor = connection.cursor()
SQLCommand = ("select ObjectId, ObjectColumnName,Label from LocalizedLabel "
"where LanguageId = 1065")
sqlUpdate_p = ("UPDATE LocalizedLabel "
"SET Label = ? "
"WHERE ObjectId = ? and ObjectColumnName = ? and LanguageId = 1065")
cursor.execute(SQLCommand)
results = cursor.fetchall()
srcDB = sqlite3.connect('crmLLDB')
jobLength = str(len(results))
i = 0
for result in results:
val = (result[0], result[1])
srcCursor = srcDB.execute('SELECT "1065" FROM crm '
'WHERE UPPER(ObjectID)= UPPER(?) AND ObjectColumnName = ?', val)
trans = srcCursor.fetchall()
for tr in trans:
updateVals = (tr[0], result[0], result[1])
cursor.execute(sqlUpdate_p, updateVals)
i += 1
connection.commit()
connection.close()
srcDB.close()