How to use MSSQL Select in Groovy - sql-server

I'm trying to access the table from a database. First I checked the connection of the database and it worked. Then I checked the close db and it worked. After I try to select couple of items from the table and print them using eachraw command.
I'm getting below error:
Wed Oct 05 07:26:01 EDT 2016:INFO:No signature of method: groovy.sql.Sql.eachrow() is applicable for argument types: (java.lang.String, Script26$_run_closure1) values: [SELECT Type,Description FROM A.dbo.Type, ...]
Possible solutions: eachRow(java.lang.String, groovy.lang.Closure), eachRow(groovy.lang.GString, groovy.lang.Closure), eachRow(java.lang.String, groovy.lang.Closure, groovy.lang.Closure), eachRow(java.lang.String, java.util.List, groovy.lang.Closure), eachRow(java.lang.String, java.util.Map, groovy.lang.Closure), eachRow(java.util.Map, java.lang.String, groovy.lang.Closure)
This is my code:
import groovy.sql.Sql
try{
def dbURL="jdbc:sqlserver://1.1.2.1:1433;databaseName=A"
def dbUsername="sa"
def dbPassword="password"
def dbDriver="com.microsoft.sqlserver.jdbc.SQLServerDriver"
def db = Sql.newInstance(dbURL,dbUsername,dbPassword,dbDriver)
def q1 = "SELECT Type,Description FROM A.dbo.Type"
db.eachrow(q1){row ->
log.info "${it.toString().Description}"
}
}catch (Exception e){
log.info "Some db error"
log.info e.getMessage()
}finally{
db.close()
}

The method is eachRow, no eachrow, and if you specify a row variable name inside the closure, you have to use 'row' instead of 'it'.
So you code should look like this:
db.eachRow(q1){row ->
log.info "${row.description}"
}

Related

AttributeError: 'NoneType' object has no attribute 'fetchall' in Prefect

I have been using the following code in production for the last couple of months,
#task
def sql_run_procs():
"""This is a delete and update..."""
# Get our logger
logger = prefect.utilities.logging.get_logger() # type: ignore
conn = connect_db(prefect.config.kv.p.prod_db_constring, logger) ## wrapper around create_engine()
with conn.connect() as con:
try:
r = con.execute(
f"EXECUTE fs.spETL_MyProc '{prefect.config.kv.p.staging_db_name}'"
).fetchall()
for q in r[0]:
if q == 1:
logger.info(f"Query {q} has failed")
raise signals.FAIL()
except :
raise SQLAlchemyError("Error in SQL Script")
So like any good coder I copy and pasted the code into another script
#task
def sql_run_procs():
"""This is a clean, truncate and insert"""
# Get our logger
logger = prefect.utilities.logging.get_logger() # type: ignore
conn = connect_db(prefect.config.kv.p.prod_db_constring, logger)
with conn.connect() as con:
try:
r = con.execute(
f"EXECUTE forms.spETL_MyOtherProc '{prefect.config.kv.p.staging_db_name}'"
).fetchall()
for q in r[0]:
if q == 1:
logger.info(f"Query {q} has failed")
raise signals.FAIL()
except :
raise SQLAlchemyError("Error in SQL Script")
And got the following error:
AttributeError: 'NoneType' object has no attribute 'fetchall'
The only difference other than the name of the stored procedure is they're in different Prefect projects. I've searched this site and others for a possible solution but had no success. I know that it's probably something staring me right in the face but after an hour and a half... you know. Thanks in advance.

How to extract data from a snowflake table into CSV using Python

import snowflake.connector
import sys
import logging
import logging.config
class opMetadataExt:
def __init__(self):
#self.logger = logging.getLogger('csv_to_json')
self.sfExtract()
def sfExtract(self):
#pwd = input("Password: ")
sqlSnowflake = snowflake.connector.connect(
user=
password=
account=
database=
role=
warehouse=
#warehouse=
schema=
)
sqlSnowflake.cursor().execute("USE WAREHOUSE ")
sqlSnowflake.cursor().execute("USE DATABASE ")
sqlSnowflake = sqlSnowflake.cursor()
test = "copy into '#/extractFile/' from (select * from information_schema.tables limit 1) file_format=(format_name=(type='csv'))"
try:
sqlSnowflake.execute(test)
rows = sqlSnowflake.fetchall() print(f'Data - {rows}')
except Exception as e:
print(e)
#sqlSnowflake.rollback()
finally:
sqlSnowflake.close()
But getting the below error:
001012 (42601): 0195a241-01fd-1365-0000-54ad01f956da: SQL compilation error:
missing stage name in URL: #/extractFile/

Kotlin: sqlite database table not creating

Iam new to Kotlin. I am developing a "personality guessing" app. it was working fine but when i added SQLite database when I run it keeps crashing when i reach to activity on which SQLite is integrated. my table does not create.
error log image here in link
Error log:
2020-06-04 13:18:10.757 16744-16744/? E/example.guessm: Unknown bits set in runtime_flags: 0x8000
2020-06-04 13:18:12.088 16744-16776/com.example.guessme E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2020-06-04 13:18:12.088 16744-16776/com.example.guessme E/eglCodecCommon: glUtilsParamSize: unknow param 0x000082da
2020-06-04 13:18:33.961 16744-16744/com.example.guessme E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.guessme, PID: 16744
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.guessme/com.example.guessme.QuizActivity}: java.lang.IllegalStateException: getDatabase called recursively
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3270)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409)
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83)
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:214)
at android.app.ActivityThread.main(ActivityThread.java:7356)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930)
Caused by: java.lang.IllegalStateException: getDatabase called recursively
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:357)
at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:317)
at com.example.guessme.DbHelper.addQuestion(DbHelper.kt:80)
at com.example.guessme.DbHelper.addQuestions(DbHelper.kt:45)
at com.example.guessme.DbHelper.onCreate(DbHelper.kt:35)
at android.database.sqlite.SQLiteOpenHelper.getDatabaseLocked(SQLiteOpenHelper.java:412)
at android.database.sqlite.SQLiteOpenHelper.getReadableDatabase(SQLiteOpenHelper.java:341)
at com.example.guessme.DbHelper.getAllQuestions(DbHelper.kt:93)
at com.example.guessme.QuizActivity.onCreate(QuizActivity.kt:29)
at android.app.Activity.performCreate(Activity.java:7802)
at android.app.Activity.performCreate(Activity.java:7791)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1299)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3245)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3409) 
at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:83) 
at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:135) 
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:95) 
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2016) 
at android.os.Handler.dispatchMessage(Handler.java:107) 
at android.os.Looper.loop(Looper.java:214) 
at android.app.ActivityThread.main(ActivityThread.java:7356) 
at java.lang.reflect.Method.invoke(Native Method) 
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:492) 
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:930) 
Code snippet of onCreate method in DbHelper class:
private val DATABASE_VERSION = 2
// Database Name
private val DATABASE_NAME = "PersonalityQuiz.db"
// tasks table name
lateinit var dbase: SQLiteDatabase
class DbHelper (context: Context) : SQLiteOpenHelper(context, DATABASE_NAME, null, DATABASE_VERSION) {
override fun onCreate(db: SQLiteDatabase) {
dbase = db
val sql = ("CREATE TABLE IF NOT EXISTS " + TABLE_QUEST + " ( "
+ KEY_ID + " INTEGER PRIMARY KEY AUTOINCREMENT, " + KEY_QUES
+ " TEXT, " + KEY_OPTA + " TEXT, "
+ KEY_OPTB + " TEXT, " + KEY_OPTC + " TEXT)")
db.execSQL(sql)
addQuestions()
db.close()
}
code snippet of addQuestions function where i insert questions to database:
// Adding new question
fun addQuestion(quest: Question) {
dbase = this.writableDatabase
val values = ContentValues()
values.put(KEY_QUES, quest.getQUESTION())
values.put(KEY_OPTA, quest.getOPTA())
values.put(KEY_OPTB, quest.getOPTB())
values.put(KEY_OPTC, quest.getOPTC())
// Inserting Row
dbase.insert(TABLE_QUEST, null, values)
}
code snipppet for onUpgrade method:
override fun onUpgrade(db: SQLiteDatabase, oldV: Int, newV: Int) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS $TABLE_QUEST")
// Create tables again
onCreate(db)
}
You cannot access writableDatabase within onCreate().
Either remove the addQuestions() call from onCreate(), or pass the SQLiteDatabase from onCreate() as a parameter to addQuestions().

Operational error at cursor when creating function in SQLite

I am trying to insert data into my SQLite database, it goes fine until I get the error while creating a function for DB. It sends OperationalError at cursor.
I couldn't find solution for my problem.
Code I'm using:
import sqlite3
from sqlite3 import *
SQL_CREATE_STATEMENT = '''CREATE TABLE password
(id integer PRIMARY KEY NOT NULL,username text, password text, source text)'''
SQL_INSERT_STATEMENT = '''INSERT INTO password (username, password, source)VALUES({},{},{});'''
DATABASE_PATH = 'home/taha/lessons/projects/passStorage/passDB.db'
DATA = dict()
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
return e
def create_table(connection, sql_commands):
c = connection.cursor()
c.execute(sql_commands)
print('done')
def get_input():
USERNAME = input('username: ')
PASSWORD = input('password: ')
SOURCE = input('source: ')
return USERNAME,PASSWORD,SOURCE
def insert_date(connection, data):
c = connection.cursor()
c.execute(SQL_INSERT_STATEMENT.format(data.values))
def main():
conn = create_connection(DATABASE_PATH)
create_table(conn, SQL_CREATE_STATEMENT)
user_info = get_input()
DATA['username'], DATA['password'], DATA['SOURCE'] = user_info
insert_date(conn, DATA)
if __name__ == '__main__':
main()
I expect no error but it sends this:
c = connection.cursor()
AttributeError: 'OperationalError' object has no attribute 'cursor'
def create_connection(db_file):
try:
conn = sqlite3.connect(db_file)
return conn
except Error as e:
return e # <-- here you return OperationalError instance
AttributeError: 'OperationalError' object has no attribute 'cursor'
Shows that OperationalError has no attribute cursor
Add additional logic that check connection here.
I believe the core of your problem is wrong file path:
DATABASE_PATH = 'home/taha/lessons/projects/passStorage/passDB.db'
But I believe should be
DATABASE_PATH = '/home/taha/lessons/projects/passStorage/passDB.db'

UUID madness with mssql

My database entry has a UUID with the value (extracted using the Microsoft SQL Server Management Studio)
CDF86F27-AFF4-2E47-BABB-2F46B079E98B
After this is loaded into my Scala application, the toString method yields this value
276ff8cd-f4af-472e-babb-2f46b079e98b
How does this happen? And how can I programmatically create a UUID instance, when I have only the bare string CDF86F27-AFF4-2E47-BABB-2F46B079E98B at hand?
Relevant Slick code (former: table definition, latter: database access object)
class ChannelTable(tag: Tag) extends Table[ChannelTuple](tag, "Channel") {
def id = column[UUID]("Id", O.PrimaryKey)
def channelId = column[Int]("Channel_Id", O.NotNull)
def timer = column[UUID]("Timer_Id", O.NotNull)
def from = column[Timestamp]("FromTime", O.NotNull)
def to = column[Timestamp]("ToTime", O.NotNull)
def mon = column[Boolean]("Mon", O.NotNull)
def tues = column[Boolean]("Tues", O.NotNull)
def wed = column[Boolean]("Wed", O.NotNull)
def thu = column[Boolean]("Thu", O.NotNull)
def fri = column[Boolean]("Fri", O.NotNull)
def sat = column[Boolean]("Sat", O.NotNull)
def sun = column[Boolean]("Sun", O.NotNull)
def * = (id, channelId, timer, from, to, mon, tues, wed, thu, fri, sat, sun)
}
object ChannelDAO extends EntityDAO[Channel, ChannelTuple] {
private val entities = TableQuery[ChannelTable]
[...]
override def get(id: UUID)(implicit session: Session): Option[Channel] = {
val y = for {
a <- entities if a.id === id
} yield (a)
if (y.list.length > 1) throw new NonUniqueResultException
y.firstOption
}
[...]
}
Slick converts a UUID to a uniqueidentifier differently then SQL Server.
endianness is unspecified in .NET / SQL Server.
Make sure to use big endian encoding for UUIDs to be consistent with the JVM if you are getting the UUID from MSSQL.
Check out this SO post. Looks like you will need to create a method to translate the UUID.
How to read a .NET Guid into a Java UUID
Works fine for me:
> val uuidString = "CDF86F27-AFF4-2E47-BABB-2F46B079E98B"
uuidString: String = CDF86F27-AFF4-2E47-BABB-2F46B079E98B
> java.util.UUID.fromString(uuidString)
res2: java.util.UUID = cdf86f27-aff4-2e47-babb-2f46b079e98b

Resources